如果我们有使用原生态的WordPress程序,在一些用户体验和搜索引擎体验设置是不够理想的,不过如果我们选择一些主题中可能会自带这些功能。比如标题自定义、关键字和描述的设置,我们一般还可以使用插件自动获取。老蒋在之前文章中也有分享过"WordPress无插件实现标题、关键字、描述自定义设置"和"WordPress SEO标题/关键字/描述优化插件 - WP SEO TDK介绍与使用",可以通过插件是修改代码。
但是,这个有一个问题,比如无插件的那方式是直接在主题头部页面修改的,但是有些头部页面是嵌套在定义脚本中的有些时候还找不到,所以我们还需要一个更为通用的方法。这篇稳重,老蒋要分享的是直接定义在主题functions.php文件中的。基本上适合所有主题。
第一、脚本内容


//自动关键词与描述
function get_cats_name() {
$allcats=get_categories();<br> foreach ($allcats as $category)<br> {<br> $keywords[] = $category->cat_name;<br> }<br> return $keywords;
}
// utf8 substr
function utf8Substr($str, $from, $len) {<br> return preg_replace('#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$from.'}'.
'((?:[x00-x7F]|xC0-xFF+){0,'.$len.'}).*#s',<br> '$1',$str);<br> }<br> // Meta SEO<br> function meta_SEO() {<br> global $post;
$output = '';<br> if (is_single()){//如果是文章页<br> $keywords = '';
$description = '';<br> if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要为描述
$description = $post->post_excerpt;
$description = str_replace("rn","",$description);
$description = str_replace("n","",$description);
$description = str_replace(""","'",$description);
$description .= '...';<br> } else {//如果文章摘要不存在就截断文章前200字为描述<br> $description = utf8Substr(strip_tags($post->post_content),0,200);<br> $description = str_replace("rn","",$description);<br> $description = str_replace("n","",$description);<br> $description = str_replace(""","'",$description);<br> $description .= '...';
}
$tags = wp_get_post_tags($post->ID);//取文章标签
foreach ($tags as $tag ) {
$keywordarray[] = $tag->name;
}
//以文章标签为关键字
$keywords = implode(',',array_unique((array)$keywordarray));
} else {//如果不是文章页
$keywords = '在引号间写入你博客的关键字用,断开';<br> $description = '在引号间写入你博客的简单描述,不要过200字';
}
//输出关键字
$output .= '<meta name="keywords" content="' . $keywords . '" />' . "n";
$output .= '<meta name="description" content="' . $description . '" />' . "n";
//输出描述
echo "$outputn";
}
add_action('wp_head', 'meta_SEO');

第二、使用方法
将上面脚本添加到当前WordPress主题中的functions.php文件中即可实现。当然,我们需要将几处信息,包括首页关键字和描述修改,其他页面都是自动的。


扫描二维码,在手机上阅读!