让WordPress自动添加Description和Keywords

08/15/2012

鉴于keyword在SEO中的关键性,如果我想给我的每篇日志前面都加上keywords。具体实现办法如下:每篇文章的内容不同,我们该如何让wordpress自动添加文章描述和关键词呢?其实办法很简单,我们只需要在模板头部添加如一段 PHP代码,让wordpress自动识别页面是首页还是文章页,当然也可以识别分类页、标签页这些。再分别为不同的页面添加不同的 Description和Keywords。

如果是文章页面,Description就自动截取文章的前220字符作为页面的描述,文章的tag就作为页面的关键词。Description是不会有乱码的哦。

1. 打开你的模板文件header.php,在最前面添加如下PHP代码:

<?php
//判断是否为首页
if (is_home()) {
    $description = '这里填写你的博客首页的描述,最多220字符';
    $keywords = '这里填写你的博客首页的关键词,用英文逗号分开';
//判断是否为文章页
} else if (is_single()) {
    if ($post->post_excerpt) {
        $description = $post->post_excerpt;
    } else {
        $description = mb_strimwidth(
        strip_tags(apply_filters('the_content',$post->post_content))
       ,0,220);
    }
    $keywords = '';
    $tags = wp_get_post_tags($post->ID);
    foreach ($tags as $tag ) {
        $keywords = $keywords . $tag->name . ',';
    }
//判断是否为分类页
} else if (is_category()) {
    $description = category_description();
}
?>

2. 查找标签:
</head>
3. 在前面加入
<meta name=”keywords” content=”<?php echo $keywords; ?>” />
<meta name=”description” content=”<?php echo $description; ?>” />
4. 大功告成!

补充:

网上有些文章提到的用如下代码截断文章办法其实不行,对于中文来说会产生乱码,甚至导致整个页面乱码:
$description = substr(strip_tags($post->post_content),0,220);

而如果我们用mb_strimwidth函数就不会了
$description = mb_strimwidth(strip_tags(apply_filters(‘the_content’,$post->post_content)),6,220);