我们在编写文章时,经常需要添加一些标签关键词的链接,这样不仅可以优化我们的内链,对用户来说也可以参照相关的文章,如果对文章的关键字进行手动添加链接,那样对我们来说太麻烦了,而且在标签关键词很多的情况下我们是记不住的,今天就向大家介绍如何让我们的wordpress文章自动添加标签关键词的链接:
打开我们主题的functions.php文件添加如下代码:
// 文章添加关键词链接//连接数量$match_num_from = 1; //一篇文章中同一个关键字少于多少次锚文本链接(这个直接填1就好了)$match_num_to = 1; //一篇文章中同一个关键字最多出现多少次描文本(建议不超过2次)//连接到WordPress的模块add_filter('the_content','tag_link',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 = "<span class=\"tag-span\"><a class=\"tag\" href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('View all posts in %s'))."\"";$url .= ' target="_blank"';$url .= ">".addcslashes($cleankeyword, '$')."</a></span>";$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;}
OK,当我们的文章出现过我们添加的标签关键词时,就会自动添加链接,你可以查看本站实例,如下图:
联系客服