保哥笔记

typecho各页面类型meta robots和canonical配置SEO规则代码

今天审查自己这个站的typecho模板,发现关于SEO的canonical和meta robots部分的规则,不是很友好。重新按SEO的技术审查要求,写了全套判断规则。
为了确保首页分页时meta robots设置正确,我们可以使用getCurrentPage()函数来判断当前页是否为分页。

分页的判断

通过 $this->getCurrentPage() > 1 判断是否为首页的分页。如果是分页页面($this->getCurrentPage() 大于 1),则输出 meta name="robots" content="noindex, follow"
同理,分类页的分页判断保持不变,若是分页,则添加 meta name="robots" content="noindex, follow"
以下是为Typecho各页面类型(首页、文章页、单页、分类页、标签页、搜索页)配置meta robots和canonical标签的代码示例。这些规则有助于优化网站的SEO。

使用方法

复制以下代码粘贴到你当前模板目录中header.php文件的<head></head>中,保存即可生效。

<?php 
if ($this->is('index')): ?>
<?php if ($this->getCurrentPage() > 1): ?>
<!-- 如果是首页的分页,则meta robots设置noindex, follow;canonical设为首页第1页 -->
<meta name="robots" content="noindex, follow">
<link rel="canonical" href="<?php $this->options->siteUrl(); ?>" />
<?php else: ?>
<!-- 首页 -->
<meta name="robots" content="follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large" />
<link rel="canonical" href="<?php $this->options->siteUrl(); ?>" />
<?php endif; ?>
<?php elseif ($this->is('post')): ?>
<!-- 文章页 -->
<meta name="robots" content="follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large" />
<link rel="canonical" href="<?php $this->permalink(); ?>" />
<!-- 单页 -->
<?php elseif ($this->is('page')): ?>
<meta name="robots" content="follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large" />
<link rel="canonical" href="<?php $this->permalink(); ?>" />
<?php elseif ($this->is('category')): ?>
<?php if ($this->getCurrentPage() > 1): ?>
<!-- 如果是分类页的分页,则meta robots设置noindex, follow;canonical设为分类页第1页 -->
<meta name="robots" content="noindex, follow">
<link rel="canonical" href="<?php echo rtrim($this->archiveUrl, '/') . '/'; ?>" />
<?php else: ?>
<!-- 分类页 -->
<meta name="robots" content="follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large" />
<link rel="canonical" href="<?php echo rtrim($this->archiveUrl, '/') . '/'; ?>" />
<?php endif; ?>
<?php elseif ($this->is('tag')): ?>
<!-- 标签页 -->
<meta name="robots" content="follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large" />
<link rel="canonical" href="<?php echo rtrim($this->archiveUrl, '/') . '/'; ?>" />    
<?php elseif ($this->is('search')): ?>
<!-- 如果是搜索页,则meta robots设置noindex, nofollow -->
<meta name="robots" content="noindex, nofollow">
<?php elseif ($this->is('archive')): ?>
<!-- 归档页,则meta robots设置noindex, follow -->
<meta name="robots" content="noindex, follow">
<link rel="canonical" href="<?php echo rtrim($this->archiveUrl, '/') . '/'; ?>" />
<?php endif; ?>

代码说明