# WordPress 文章中的标签Tag自动增加链接

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/2454.html | 发布：2021-12-02 | 更新：2021-12-02 | 分类：建站教程

越了解WordPress发现，WordPress的生态真的太厉害了，需要的功能基本搜索一下就会有现成的了。

 

最近小编在写WordPress主题嘛，想着以前写文章总是要手动给标签添加链接就很麻烦，百度一番就给出了答案，自动给文章中出现的标签Tag增加链接，这不就方便多了嘛。

 

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

 

```
/**
 * WordPress 自动为文章标签添加该标签的链接
 * https://www.wpdaxue.com/auto-add-tag-link.html
 */
function wpkj_auto_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 = '<a target="_blank" href="'.$link.'" title="'.str_replace('%s', addcslashes($cleankeyword, '$'), __('View all posts in %s')).'">'.addcslashes($cleankeyword, '$').'</a>';
            $regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s';
            $content = preg_replace($regEx,$url,$content,$limit);
        }
    }

    return $content;
}
add_filter( 'the_content', 'wpkj_auto_add_tag_link', 1 );
```

 

看到这个代码之后，小编还想到了扩展这个功能的想法，就是在主题设置中给出让用户自己选择是否开启此功能、一篇文章出现多少个标签链接，同一个标签添加多少次链接的功能。这个方法后续会整理出教程来

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
