WordPress 自动添加关键词keywords和描述description

WordPress如何动添加关键词keywords和描述description?因为懒人懒得手动设置关键词keywords和描述description,所以我们可以实现自动添加。方法如下:

//自动关键词与描述
function get_cats_name() {
$allcats=get_categories();
foreach ($allcats as $category)
{
$keywords[] = $category->cat_name;
}
return $keywords;
}
// utf8 substr
function utf8Substr($str, $from, $len) {
return preg_replace(‘#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,’.$from.’}’.
‘((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,’.$len.’}).*#s’,
‘$1’,$str);
}
function meta_SEO() {
global $post;
$output = ”;
if (is_single()){//如果是文章页
$keywords = ”;
$description = ”;
if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要为描述
$description = $post->post_excerpt;
$description = str_replace(“\r\n”,””,$description);
$description = str_replace(“\n”,””,$description);
$description = str_replace(“\””,”‘”,$description);
$description .= ‘…’;
} else {//如果文章摘要不存在就截断文章前200字为描述
$description = utf8Substr(strip_tags($post->post_content),0,200);
$description = str_replace(“\r\n”,””,$description);
$description = str_replace(“\n”,””,$description);
$description = str_replace(“\””,”‘”,$description);
$description .= ‘…’;
}
$tags = wp_get_post_tags($post->ID);//取文章标签
foreach ($tags as $tag ) {
$keywordarray[] = $tag->name;
}
//以文章标签为关键字
$keywords = implode(‘,’,array_unique((array)$keywordarray));
} else if (is_category()){
$description = strip_tags(trim(category_description()));
$keywords = single_cat_title(”, false);
}else {//如果不是文章页、分类页
$keywords = ‘关键词1,关键词2’; //在引号间写入你博客的关键字用,断开
$description = ‘这儿是描述,自己填’;//在引号间写入你博客的简单描述,不要过200字
}
//输出关键字
$output .= ” . “\n”;
$output .= ” . “\n”;
//输出描述
echo “$output”;
}

然后把  <?php echo meta_SEO(); ?> 加到主题的header.php中(放在标题下)。