WordPress 网站必备:自动为文章外链添加 nofollow,提升网站安全与权重

在进行网站 SEO 优化时,为 WordPress 文章里的外链添加 nofollow 标签是常见操作,这样能告知…

WordPress 网站必备:自动为文章外链添加 nofollow,提升网站安全与权重
在进行网站 SEO 优化时,为 WordPress 文章里的外链添加 nofollow 标签是常见操作,这样能告知搜索引擎无需追踪这些链接。手动添加该标签虽然可行,但要是文章中的外链数量较多,操作起来就会十分繁琐,还会降低工作效率。在此,我给大家分享一个能自动为 WordPress 文章外链添加 nofollow 标签的方法,希望能帮到各位。
我曾在网上搜索了大量相关代码,然而很多要么存在错误,要么根本无法使用。经过不懈尝试,我终于找到了正确可用的代码,并且亲自测试过,效果良好。这个方法极为简单,你只需将下面的代码添加到主题目录下的 functions.php 文件中就行。
//给文章外链添加nofollow

function add_image_alt_title_tags($content) {
global $post;
$post_title = $post->post_title;
$pattern = '/<img(.*?)\/>/i';
preg_match_all($pattern, $content, $matches);
foreach ($matches[0] as $index => $img_tag) {
if (strpos($img_tag, ' alt=') === false || preg_match('/ alt=["\']\s*["\']/', $img_tag)) {
$replacement = preg_replace('/<img/', '<img alt="' . $post_title . ' ' . ($index + 1) . '" title="' . $post_title . ' ' . ($index + 1) . '"', $img_tag);
$content = str_replace($img_tag, $replacement, $content);
}
}
return $content;
}
add_filter('the_content', 'add_image_alt_title_tags');

//文章外链nofollow结束

免责声明 本站提供的一切内容仅限用于学习和研究目的,不得将上述内容用于商业或者非法用途;
本网站内容来自互联网,版权争议与本站无关;如有侵权,请联系我们处理,谢谢!

为您推荐: