1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > php给文章关键词加内链 WordPress 自动为文章标签关键词 (tag) 添加内部链接

php给文章关键词加内链 WordPress 自动为文章标签关键词 (tag) 添加内部链接

时间:2023-07-23 22:20:18

相关推荐

php给文章关键词加内链 WordPress 自动为文章标签关键词 (tag) 添加内部链接

这两天在给自己的网站做一些小小的 SEO 优化,比如增加一些内链。手动增加当然是太繁琐了,于是就想到了自动增加。下面就分享一下 WordPress 中自动为文章的标签添加内链的方法。

方法比较简单,在后台编辑主题的地方,找到 functions.php,然后在该文件最后添加上下面的代码即可:/**

* WordPress 自动为文章标签添加该标签的链接

* /auto-add-tag-link.html

*/

$match_num_from = 1; // 一个标签在文章中出现少于多少次不添加链接

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

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

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

";

$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;

}

可以根据自己的需要修改文章标签的链接数。

亲自测试了,很好用。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。