WordPress 纯代码实现标签自动内链及自动添加标签

1,058次阅读
没有评论

最近用了一款puock的主题,然后用上了php8.0。开了一个新站,用火车头v9.8各种采集数据。后来想到,弄一下内链,于是开始各种找网上的插件。

结果发现要么插件不能对已有文章加内链,要么就是已经没了,后来找了网上的一些代码, 发现不支持php8.0,弄上就报错。

正好,有个群友给了一段代码,我试了试内链,还不错,就记录下来。

一、标签自动链接

将以下代码添加到当前主题的functions.php文件中保存:

/* 自动为文章内的标签添加内链 */
function xy_add_tag_link($content){
$limit = 1; // 设置同一个标签添加几次链接
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
$cleankeyword = stripslashes($keyword);
$url = ''.addcslashes($cleankeyword, '$').'';
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?))\'s';
$content = preg_replace($regEx,$url,$content,$limit);
}
}
return $content;
}
add_filter( 'the_content', 'xy_add_tag_link', 1 );

 

WordPress文章自动添加标签:

/* 自动为文章添加标签 */
add_action('save_post', 'xy_add_tags');
function xy_add_tags(){
$tags = get_tags( array('hide_empty' => false) );
$post_id = get_the_ID();
$post_content = get_post($post_id)->post_content;
if ($tags) {
foreach ( $tags as $tag ) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if ( strpos($post_content, $tag->name) !== false)
wp_set_post_tags( $post_id, $tag->name, true );
}
}
}

 
吾爱互联
版权声明:本站原创文章,由 吾爱互联 2022-05-16发表,共计1020字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
载入中...