WordPress实现文章自动提取tag并添加链接

2023-08-27 4045阅读 0评论
Kdatacenter:$17.1/月/1G内存/100GB SSD空间/1TB流量/1Gbps端口/KVM/韩国SK/直连;原生IP


WordPress里要实现文章自动提取tag方法有很多,最方便的使用插件。今天分享一个不用插件来实现文章的自动提取tag并添加链接的方法。
登录博客后台,打开博客主题的function.php功能函数,在这个文件里面添加如下代码:

//连接数量
$match_num_from = 1; //一个关键字少于多少不替换
$match_num_to = 10; //一个关键字最多替换
//连接到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 = " $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;
}

纯粹为自己使用方便。

WordPress实现文章自动提取tag并添加链接 第1张
(图片来源网络,侵删)

免责声明
1、本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明。
2、本网站转载文章仅为传播更多信息之目的,凡在本网站出现的信息,均仅供参考。本网站将尽力确保所
提供信息的准确性及可靠性,但不保证信息的正确性和完整性,且不对因信息的不正确或遗漏导致的任何
损失或损害承担责任。
3、任何透过本网站网页而链接及得到的资讯、产品及服务,本网站概不负责,亦不负任何法律责任。
4、本网站所刊发、转载的文章,其版权均归原作者所有,如其他媒体、网站或个人从本网下载使用,请在
转载有关文章时务必尊重该文章的著作权,保留本网注明的“稿件来源”,并白负版权等法律责任。

手机扫描二维码访问

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,4045人围观)

还没有评论,来说两句吧...

目录[+]