以下代码实现的是以标签为关键词;以摘要为描述,如果没有填写摘要,那就自动截取文章前200字为描述。(教程转自:DeveWork)

代码实现WordPress自动关键词与描述:

以下代码放到你的主题下funtions.php的最后一个 ?>前:

//自动关键词与描述 
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);
}
// Meta SEO
function meta_SEO() {
global $post;
$output = '';
if (is_single()){//如果是文章页
$keywords = '';
$description = '';
if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要为描述
$description = $post->post_excerpt;
$description = str_replace("rn","",$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("rn","",$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 {//如果不是文章页
$keywords = '嬴冰博客,一家专注于专注于技术与资源分享的自媒体站点。极客资讯,前端应用技术,源码分享,实战经验,军事理论分享,历史解密与好玩的有趣的热点资讯分享!'; //在引号间写入你博客的关键字用,断开
$description = '嬴冰博客,一家专注于专注于技术与资源分享的自媒体站点。';//在引号间写入你博客的简单描述,不要过200字
}
//输出关键字
$output .= '<meta name="keywords" content="' . $keywords . '" />' . "n";
$output .= '<meta name="description" content="' . $description . '" />' . "n";
//输出描述
echo "$outputn";
}
add_action('wp_head', 'meta_SEO');//添加meta_SEO函数到头部信息里