Wordpress/WordPress教程

WordPress非插件代码实现文章内关键词自动内链设置

魂Soul · 20-02-24 · 1,786

前言

网站内链建设对网站seo优化肯定是必不可少的,但是每次自己手动设置就比较麻烦,耗费时间了,所以在 WordPress种实现自动文章内链是很有必要的。

实现方法

文章自动内链 在WordPress种的实现方法,其实有一款 Auto Tags Link 的插件就可以实现,但是就这么一个小功能又装一个插件太费事了,所以这里才提供了一个代码版的,将以下代码添加到当前主题的 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){
$match_num_from = 1; //一个标签少于几次不链接
$match_num_to = 1; //一个标签最多链接几次
$posttags = get_the_tags();
if ($posttags) {
usort($posttags, "tag_sort");
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
//链接代码
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('更多关于 %s 的文章'))."\"";
$url .= ' target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);
//不链接代码
$content = preg_replace( '|(<a[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
}
}
return $content;
}
add_filter('the_content','tag_link',1);

提醒注意

以上代码只支持 tag 标签关键词链接,就是在发布文章时自己设置的tag标签,如果在文章中出现了,那么就把首次出现的关键词设置为内链。

0 条回应