WordPress网站做SEO优化时,内链是一个很重要的因素,而我们平时都是手动为文章添加内链,这样会增加一些时间,其实我们可以让网站自动为文章生成标签,并且为标签自动添加内链。虽然有很多的插件可以实现这个功能,但是我们还是尽量使用纯代码来实现。

本文所有内容均添加到子比主题目录下functions.php文件里面

WordPress文章自动添加标签的代码

它的用途是在写完文章发布的时候,自动检测这篇文章中有的关键字,然后把这个关键字转成标签添加进去,这个貌似需要在后台发布文章才可以生效,也可以在前台编辑完文章发布,然后到后台再发布一遍。

add_action('save_post', 'auto_add_tags');

function auto_add_tags()

{

$tags = get_tags(array('hide_empty' => false));

$post_id = get_the_ID();

$post_content = get_post($post_id)->post_content;

if ($tags) {

foreach ($tags as $tag) {

// 如果文章内容出现了已使用过的标签,自动添加这些标签

if (strpos($post_content, $tag->name) !== false) {

wp_set_post_tags($post_id, $tag->name, true);

}

}

}

}

WordPress自动为标签添加内链的代码

它的用途就是你在写这篇文章的时候,如果添加了标签,它会自动把文章内含有标签的字添加成内链。

//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 = "

$url .= ' target="_blank"';

$url .= ">".addcslashes($cleankeyword, '$')."";

$limit = rand($match_num_from,$match_num_to);

//不链接代码

$content = preg_replace( '|(]+>)(.*)('.$ex_word.')(.*)<\/pre>(]*>)|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);

直接放主题目录下functions.php文件里面。

👋 感谢您的观看!