WordPress SEO优化 如何自动为文章添加标签链接增加站点内链

关于wordpress程序的SEO优化,柠檬也有点迷茫,插件太多。先不纠结插件的问题,我们先把SEO基础做好。 这篇教程是做网页TAG内联的。路途吧本站所有教程优先使用免插件版。

怎么自动为wordpress文章内的TAG添加内联?

WordPress纯代码实现自动添加文章标签链接的方法?其实很简单,我们只需在自己主题的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 = \\\\\\\"<a href=\\\\\\\\\\\\\\\"$link\\\\\\\\\\\\\\\" title=\\\\\\\\\\\\\\\"\\\\\\\".str_replace(\\\\\\\'%s\\\\\\\',addcslashes($cleankeyword, \\\\\\\'$\\\\\\\'),__(\\\\\\\'【查看含有[%s]标签的文章】\\\\\\\')).\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\";
                $url .= \\\\\\\' target=\\\\\\\"_blank\\\\\\\"\\\\\\\';
                $url .= \\\\\\\">\\\\\\\".addcslashes($cleankeyword, \\\\\\\'$\\\\\\\').\\\\\\\"</a>\\\\\\\";
                $limit = rand($match_num_from,$match_num_to);
                $content = preg_replace( \\\\\\\'|(<a[^>]+>)(.*)(\\\\\\\'.$ex_word.\\\\\\\')(.*)(</a[^>]*>)|U\\\\\\\'.$case, \\\\\\\'$1$2%&&&&&%$4$5\\\\\\\', $content);
                $content = preg_replace( \\\\\\\'|(<img)(.*?)(\\\\\\\'.$ex_word.\\\\\\\')(.*?)(>)|U\\\\\\\'.$case, \\\\\\\'$1$2%&&&&&%$4$5\\\\\\\', $content);
                $cleankeyword = preg_quote($cleankeyword,\\\\\\\'\\\\\\\\\\\\\\\'\\\\\\\');
                $regEx = \\\\\\\'\\\\\\\\\\\\\\\'(?!((<.*?)|(<a.*?)))(\\\\\\\'. $cleankeyword . \\\\\\\')(?!(([^<>]*?)>)|([^>]*?</a>))\\\\\\\\\\\\\\\'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);

 

柠檬有话说:

把上面代码添加到functions.php文件后,当我们发布、更新、保存文章时,会自动检测文章中是否有标签关键词,如果有就会自动添加这些标签的链接。如这篇文章有标签:路途吧,那么只要我们的文章内容中出现有路途吧的关键词,那么就会自动为“路途吧”添加标签链接变成内链。

只要我们站点的Tag标签够多的情况下,使用这两个代码以实现WordPress站点自动为文章添加标签和标签内链,那么将会大大减少我们的工作量。如果大家平时不喜欢人工添加标签的,不妨试试这个方法。

注意事项:

上面代码中$match_num_to = 1; //一篇文章中同一个标签最多自动链接几次,这个建议最多只设置3次。