不凡博客(Bufanz.com)

版权声明

未经允许,请勿转载本博客的文章、图片和视频,谢谢!
首页 > WordPress > 正文

WordPress文章内容匹配标签自动添加内链(代码版)

WordPress | 2021年06月04日10:33:01

腾讯云轻量服务器2核2G3M仅88元/年

功能简介

  前台文章内容中如果有存在的文章标签关键词,自动添加内链,有利于SEO。此功能是无插件代码版。

效果截图

WordPress文章内容匹配标签自动添加内链(代码版)

代码

/*
*Wordpress文章内容匹配标签自动添加内链
*/
//连接数量
$match_num_from = 1; //一篇文章中同一个关键字少于多少不锚文本(这个直接填1就好了)
$match_num_to = 1; //一篇文章中同一个关键字最多出现多少次锚文本(建议不超过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;
}

代码出处:https://www.npc.ink/15286.html

代码添加方法

后台的外观 > 主题编辑器 > 选择主题 > 点击"functions.php" > 粘贴代码到文件内容中 > 更新文件

WordPress文章内容匹配标签自动添加内链(代码版)

The End
淘宝购物先领券,更省钱

本文标题:WordPress文章内容匹配标签自动添加内链(代码版)

本文链接:https://bufanz.com/post/161.html

版权声明:本文章是 不凡博客(Bufanz.com) 的原创文章,未经允许请勿转载本文章!

网友点评 展开评论

本文暂无评论 - 欢迎您

请填写验证码