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

文章目录

关于WordPress SEO优化本站也简介过一点皮毛,因为本站也是小白,不会怎么做SEO优化,都是学习前辈的WordPress教程,大多都是按部就班。在此文章中本站将为大家分享一个无需任何插件,纯代码实现“自动为WordPress文章添加标签链接从而实现增加站点内链”。说是分享,其实是为了记录以下,方便自己以后查找,因为此方法百度一搜,比比皆是。话说回来虽然百度能搜到有一大把,但是有些细节问题还是要注意,并不是都是非常完美的。具体方法如下:

如何自动为WordPress文章添加标签链接增加站点内链?WordPress纯代码实现自动添加文章标签链接的方法?其实很简单,我们只需在自己主题的functions.php文件最后一个?>前添加下面代码即可。

自动标签链接代码

//WordPress 文章关键词自动内链 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){ $match_num_from = 1; //一个标签少于几次不链接 $match_num_to = 1; //一个标签最多链接几次 $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);

//自动TAG转内链 $match_num_from = 1; // 一个TAG标签出现几次才加链接 $match_num_to = 1; // 同一个标签加几次链接 add_filter('the_content','tag_link',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; }

注意事项:

把上面代码添加到functions.php文件后,当我们发布、更新、保存文章时,会自动检测文章中是否有标签关键词,如果有就会自动添加这些标签的链接。虽然是自动的,但我们还需注意以下两点:

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

2、代码中的$posttags = get_tags();表示自动为文章添加全站所有标签链接,我们还可以改成只为此文章设置的标签添加链接,只需将“$posttags = get_tags();”改成“$posttags = get_the_tags();”即可。

一般建议使用本站推荐代码,无需做任何修改。

推荐站内搜索:注册 域名、主机服务器租用、工信部网站备案系统我的ip地址、国内代理服务器ip、国内免备案空间、美国免费虚拟主机、海外服务器租用的价格、cn域名价格、德国服务器、