总所周知,网站内链(指网站内部的相关信息互相连接)是非常重要的,不仅针对于SEO优化,对于用户的访问也是非常有利的,你可以将文章中出现的一些关键添加上连接,这样这些重要的信息就能够被用户点击所看到,增强网站内容的粘性,让用户能够更容易的找到你的内容。
如果我们手动进行关键词的链接添加,这无疑是一个非常繁琐的工作,因此我们用函数代码实现,这样也能减少使用插件。如果你嫌麻烦,或者想拥有更加强大的内链功能emmm还是用插件吧。
在主题的functions文件中添加以下代码:
/*
*Wordpress文章关键词自动添加内链链接代码
*/
//连接数量
$match_num_from = 1; //关键字标签出现几次才加链接
$match_num_to = 1; //同一个关键字标签加几次链接
//连接到WordPress的模块
add_filter('the_content','tag_link',1);
//按长度排序
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){
global $match_num_from,$match_num_to;
$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[^>]+>)(.*)('.$ex_word.')(.*)(</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;
}
特别声明:本站大部分资源来源于网络,如若本站内容有侵犯了原著者的合法权益,请联系邮箱"admin@liitk.com"提供证明并给予删除处理!