无论是什么样的网站,内链的建设都是必不可缺的。我们都知道外部链接可以提高网站权重,进而促使排名靠前。
一、标签自动链接
将以下代码添加到当前主题的functions.php文件中保存:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/* 自动为文章内的标签添加内链开始 */ $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, '$'),__('View all posts in %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文件中保存:
1 2 3 4 5 6 7 8 9 10 11 12 |
/* 文章指定关键词添加内链开始 */ function replace_text_wps($text){ $replace = array( '张弦先生' => '<a href="https://www.chrafz.com/" target="_blank" title="张弦先生">张弦先生</a>', '张弦先生博客' => '<a href="https://www.chrafz.com/blog" target="_blank" title="张弦先生博客">张弦先生博客</a>', '设计' => '<a href="https://www.chrafz.com/projects" target="_blank" title="设计">设计</a>' ); $text = str_replace(array_keys($replace), $replace, $text); return $text; } add_filter('the_content', 'replace_text_wps'); |
自行将代码中的关键词与链接换成自己的,需要其他关键词复制那一行代码即可,非常方便,这个方法有个缺陷就是不能控制关键词锚文本次数,只要在文章中出现的关键词不管几次都会加上链接,如果大家觉得不好用,chrafz推荐使用插件实现文章关键词内链。
评论抢沙发