云服务器免费试用

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

服务器知识 0 1414

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

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

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

方法比较简单,在后台编辑主题的地方,找到 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;}

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

亲自测试了,很好用。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942@qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: WordPress 自动为文章标签关键词 (tag) 添加内部链接
本文地址: https://solustack.com/5784.html

相关推荐:

网友留言:

我要评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。