Dynadot Jtti 搬瓦工 腾讯云

WordPress 自动为文章标签关键词 (tag) 添加内部链接

GigsGigsCloud

这两天在给自己的网站做一些小小的 SEO 优化,比如增加一些内链。手动增加当然是太繁琐了,于是就想到了自动增加。下面就分享一下 WordPress 中自动为文章的标签添加内链的方法。

方法比较简单,在后台编辑主题的地方,找到 functions.php,然后在该文件最后添加上下面的代码即可:

/**
 * WordPress 自动为文章标签添加该标签的链接
 * https://www.wpdaxue.com/auto-add-tag-link.html
 */
$match_num_from = 1;  // 一个标签在文章中出现少于多少次不添加链接
$match_num_to = 1; // 一篇文章中同一个标签添加几次链接
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, '$'),__('View all posts in %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;
}

可以根据自己的需要修改文章标签的链接数。

亲自测试了,很好用。

文章来源:https://www.wpdaxue.com/auto-add-tag-link.html

Dynadot Hostwinds
赞(2)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《WordPress 自动为文章标签关键词 (tag) 添加内部链接
文章链接:https://oldtang.com/335.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。