前言
今天给大家分享一个WordPress SEO优化小技巧,该技巧能够实现文章内的关键词标签自动添加内链。
内链的好外,自然就不用说了,它可以让百度蜘蛛在你的网站爬行更多的地方。
当然,很多WordPress插件也可以实现这个功能,但是今天素材虎给大家分享的是不用插件给文章关键词标签自动添加内链的方法。
那怎么如何让WordPress站点的文章关键词标签自动添加内链呢?其实我们只需要在主题目录下的functions.php文件中添加一段代码就可以实现了。
效果图
食用方法
在主题目录下的functions.php文件中添加下方代码就可以实现了WordPress给文章关键词标签自动添加内链。
/* 自动为文章内的标签添加内链开始 */
function tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
// 为符合条件的标签添加链接
function tag_link($content){
$posttags = get_the_tags();
$match_num_from = 2; // 一个标签在文章中出现少于多少次不添加链接
$match_num_to = 5; // 一篇文章中同一个标签添加几次链接
if ($posttags) {
usort($posttags, "tag_sort");
//var_dump($posttags);
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
//链接的代码
$cleankeyword = stripslashes($keyword);
$url = "";
$limit = rand($match_num_from,$match_num_to);
//不链接的代码
$pattern = "/(.*?)<\/code>/is"; // 匹配 标签
$content = preg_replace_callback(
$pattern,
static function($matches) use ($cleankeyword) {
return str_replace($cleankeyword, '%&&&&&%', $matches[0]);
},
$content
);
$title_pattern = "/<(h[1-6]).*?>(.*?)<\/\\1>/is";
$content = preg_replace_callback(
$title_pattern,
static function($matches) use ($cleankeyword) {
return str_replace($cleankeyword, '%&&&&&%', $matches[0]);
},
$content
);
$pre_pattern = "/(.*?)<\/pre>/is";
$content = preg_replace_callback(
$pre_pattern,
static function($matches) use ($cleankeyword) {
return str_replace($cleankeyword, '%&&&&&%', $matches[0]);
},
$content
);
//$content = preg_replace( '|(]+>)(.*)('.$ex_word.')(.*)(]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
//$content = preg_replace( '|(
)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(]*?)>)|([^>]*? ))\'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($cleankeyword), $content);
}
}
return $content;
}

