WordPress自动为文章中的关键词添加链接(不用插件)

释放双眼,带上耳机,听听看~!

2019042315255947.jpg插图

打开主题的functions.php文件,在末尾添加如下代码:

/* 自动为文章内的标签添加内链开始 */
$match_num_from = 1;        //一篇文章中同一个标签少于几次不自动链接
$match_num_to = 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 = "";
                $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);
/* 自动为文章内的标签添加内链结束 */

添加代码后,再看看我们添加过关键词标签的文章,是不是已经自动添加了链接?添加关键词链接的个数可以修改第一、二行代码的数值,为了防止SEO优化过度,建议最多添加2个重复的关键词锚文本。不过,这个代码不能自动识别大小写,标签中单词如果大小写跟文章不一致就不会加链接,这时候我们可以加上一行将文章大小写强制改成标签大小写的代码:

//将大小写强行更改为标签的大小写 (可能会出错,大家可以试试。)
             $content = str_ireplace(urldecode($tag->slug), $tag->name, $content);

给TA打赏
共{{data.count}}人
人已打赏

相关文章

WordPressWP代码网页建站

浏览器右侧滚动条美化 – WordPress教程

2023-2-10 18:01:50

WordPressWP代码教程

删除WordPress后台标题后缀的方法?

2023-2-12 10:55:49

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索