html提取keywords,无插件实现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 .= '' . "n";

$output .= '' . "n";

//输出描述

echo "$outputn";

}

add_action('wp_head', 'meta_SEO');

第二、使用方法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值