PHP 文章内链的实现方法,WordPress非插件代码实现文章内关键词自动内链设置

bdd7e7201e581851966f670e56674bb8.png

前言

网站内链建设对网站seo优化肯定是必不可少的,但是每次自己手动设置就比较麻烦,耗费时间了,所以在 WordPress种实现自动文章内链是很有必要的。

实现方法

文章自动内链 在WordPress种的实现方法,其实有一款 Auto Tags Link 的插件就可以实现,但是就这么一个小功能又装一个插件太费事了,所以这里才提供了一个代码版的,将以下代码添加到当前主题的 functions.php 文件中就可以了。

//WordPress 文章关键词自动内链

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 = "

$url .= ' target="_blank"';

$url .= ">".addcslashes($cleankeyword, '$')."

";

$limit = rand($match_num_from,$match_num_to);

//不链接代码

$content = preg_replace( '|(]+>)(.*)('.$ex_word.')(.*)(]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);

$content = preg_replace( '|()|U'.$case, '$1$2%&&&&&%$4$5', $content);

$cleankeyword = preg_quote($cleankeyword,'\'');

$regEx = '\'(?!((<. .>]*?)>)|([^>]*?))\'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);

提醒注意

以上代码只支持 tag 标签关键词链接,就是在发布文章时自己设置的tag标签,如果在文章中出现了,那么就把首次出现的关键词设置为内链。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值