WordPress 文章页面适当添加关键词内链链接有利于 SEO 优化,同时方便读者查看所有相关关键词的文章,区分英文与中文关键词可以对每个关键词进行细节设置,荒岛本次带来 WordPress 文章关键词自动添加链接的教程,只要将下面的代码添加到主题的「functions.php」文件即可。
// 荒岛一座藏有宝藏的小岛
$match_num_from = 1;
$match_num_to ='chain_n';
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;
if (preg_match_all('|(<h[^>]+>)(.*?)'.$keyword.'(.*?)(</h[^>]*>)|U', $content, $matchs)) {continue;}
if (preg_match_all('|(<a[^>]+>)(.*?)'.$keyword.'(.*?)(</a[^>]*>)|U', $content, $matchs)) {continue;}
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('查看与 %s 相关的文章', 'begin' ))."\"";
$url .= ' target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);
global $ex_word;
$case = "";
$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;
}
宝藏内容来自荒岛-https://x-imagine.com/wordpress-article-keywords-automatically-add-links.html宝藏内容来自荒岛-https://x-imagine.com/wordpress-article-keywords-automatically-add-links.html 请按「Ctrl+D」收藏荒岛分享给好友,如您发现本文教程或宝藏链接已失效,请联系站长修正!
荒岛公众号
扫一扫关注
HDsoft27
公众号ID已复制,前往微信关注...
荒岛哔哩姬
扫一扫关注
ximagine
哔哩姬ID已复制,前往B站关注...














