蜗牛789
主机测评与优惠

无插件实现WordPress自动获取关键字(keywords)、描述(description)

如果我们有使用原生态的WordPress程序,在一些用户体验和搜索引擎体验设置是不够理想的,不过如果我们选择一些主题中可能会自带这些功能。比如标题自定义、关键字和描述的设置,我们一般还可以使用插件自动获取。蜗牛在之前文章中也有分享过\”WordPress无插件实现标题、关键字、描述自定义设置\”和\”WordPress SEO标题/关键字/描述优化插件 – WP SEO TDK介绍与使用\”,可以通过插件是修改代码。

但是,这个有一个问题,比如无插件的那方式是直接在主题头部页面修改的,但是有些头部页面是嵌套在定义脚本中的有些时候还找不到,所以我们还需要一个更为通用的方法。这篇稳重,蜗牛要分享的是直接定义在主题functions.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\’);

第二、使用方法

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

About 蜗牛

【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。





评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址