内链优化是SEO优化的重要一环,之前博客没有添加内链是因为tags标签页robots禁止了,如今打算看看tags标签页是否也能参与排名,看看表现如何。那么,wordpress博客系统应该如何实现tags标签自动内链呢?
代码示例
//WordPress 文章关键词自动内链 添加到functions.php文件中
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);
注意
以上代码在标签获取时获取的是当前文章的tags标签,但是本身文章页就有该文章的标签链接,其实作用不大,如果需要网站所有链接都自动添加,可以修改获取tags对象的函数实现
如果是获取全部tags标签,数据多的话可能导致响应变慢,建议配合缓存插件使用
如果不想链接一些不必要的代码中的tag,比如pre标签,h标签等,可以通过正则过滤
如果内链过多,同时由于A标签的颜色导致阅读不适,可以在生成的A标签中添加class改为正文同色,同时以下划线虚线来进行标注
转载请注明:思享SEO博客 » wordpress纯代码实现tags标签自动内链