WordPress如何自动为外链添加nofollow和实现新窗口打开?

WordPress国产主题推荐

有些站长想要为外链添加rel=nofollow标签和target=_blank标签,不管是用经典编辑器,还是块编辑器,操作都相对比较“复杂”。其实,我们也可以使用WordPress插件来自动添加这两个标签,比如以下两个插件:

但是有些站长不喜欢使用插件显示,想要通过纯代码实现。网络上看了很多篇有关代码自动为外链添加rel=nofollow标签和target=_blank标签的文章,都不太满意,有些设置会重复添加多个标签,最后发现林风网络站长分享的代码非常不错,具体如下:

/*
Function Name: Automatically add nofollow to external links
Description: Automatically add nofollow attribute to article/page external links
Version: 1.0
Author: https://www.linfengnet.com/
*/
add_filter( 'the_content', 'add_nofollow_to_external_links');
function add_nofollow_to_external_links( $content ) {
// Regular expression to match all anchor tags in the content
$anchorTagRegexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";

if(preg_match_all("/$anchorTagRegexp/siU", $content, $matches, PREG_SET_ORDER)) {
if( !empty($matches) ) {
$siteUrl = get_option('siteurl');
$newContent = $content;

foreach($matches as $match) {
$originalTag = $match[0];
$modifiedTag = $originalTag;
$url = $match[0];

// Add target="_blank" if not already present
if (!preg_match('/target\s*=\s*"\s*_blank\s*"/', $modifiedTag)) {
$modifiedTag = rtrim($modifiedTag, '>') . ' target="_blank">';
}

// Add rel="noreferrer noopener nofollow" if not already present
if (!preg_match('/rel\s*=\s*"\s*[n|d]ofollow\s*"/', $modifiedTag)) {
$modifiedTag = rtrim($modifiedTag, '>') . ' rel="noopener nofollow">';
}

// Check if the URL is external
if (strpos($url, $siteUrl) === false) {
$newContent = str_replace($originalTag, $modifiedTag, $newContent);
}
}

$content = $newContent;
}
}

return $content;
}

以上代码来自@林风网络

也就是说,WordPress文章和页面的外链想要自动添加nofollow和实现新窗口打开,只需要将以上代码复制粘贴到自己网站当前使用的主题的functions.php文件中,并保存更新文件即可。

文章创作不易,期待您的评分

本文地址:https://boke112.com/article/p8164.html

版权声明:本文内容来源于互联网资源,由 boke112百科 整理汇总!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu