WordPress 自动为文章标签(关键词)添加该标签的链接

将下面的代码添加到主题的 functions.php 即可。

function jose_auto_add_tag_link($content){
    if (is_singular('post') && in_the_loop() && is_main_query()) {

        global $post;
        $limit = 1; // 每个标签最多替换几次
        $posttags = get_the_tags($post->ID);

        if ($posttags) {
            // 长词优先,避免部分词破坏结构
            usort($posttags, function($a, $b){
                return mb_strlen($b->name) - mb_strlen($a->name);
            });

            foreach ($posttags as $tag) {
                $keyword = preg_quote($tag->name, '/');
                $link = get_tag_link($tag->term_id);
                $url = '<a target="_blank" href="'.%20esc_url($link)%20.'" rel="noopener">name)) .'">'. $tag->name .'</a>';

                $pattern = '/(?!<[^>]*)(?<![=\w])('. $keyword .')(?![\w])(?![^<]*>)/u';

                $i = 0;
                $content = preg_replace_callback($pattern, function($matches) use ($url, &$i, $limit){
                    $i++;
                    return ($i <= $limit) ? $url : $matches[0];
                }, $content);
            }
        }
    }
    return $content;
}
add_filter('the_content', 'jose_auto_add_tag_link', 20);

你可以根据自己的需要修改第5行的数值。

版权声明:
作者:José
链接:https://www.josejang.com/about-work/354.html
来源:José's ⎝⏠⏝⏠⎠ Blog
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>