WordPress站外链接自动添加target=”_blank”与rel=”nofollow”属性方法

2022-09-02 0 333

学过HTML的朋友应该都知道,a标签超链接中的target=”_blank”属性是以新标签打开链接的意思,而rel=”nofollow”属性是告诉搜索引擎不要传递网站权重。

所以,我们有必要给WordPress网站中的站外链接添加上target=”_blank”与rel=”nofollow”两个属性,具体实现方法如下:

/* 自动给站外链接添加nofollow属性和新标签打开属性 https://www.fxe.cc*/
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_nf_url_parse( $content ) {
	$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
	if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
		if( !empty($matches) ) {
			$srcUrl = get_option('siteurl');
			for ($i=0; $i < count($matches); $i++)
			{
				$tag = $matches[$i][0];
				$tag2 = $matches[$i][0];
				$url = $matches[$i][0];
				$noFollow = '';
				$pattern = '/target\s*=\s*"\s*_blank\s*"/';
				preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
				if( count($match) < 1 )
					$noFollow .= ' target="_blank" ';
				$pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
				preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
				if( count($match) < 1 ) $noFollow .= ' rel="nofollow" '; $pos = strpos($url,$srcUrl); if ($pos === false) { $tag = rtrim ($tag,'>');
					$tag .= $noFollow.'>';
					$content = str_replace($tag2,$tag,$content);
				}
			}
		}
	}
	$content = str_replace(']]>', ']]>', $content);
	return $content;
}

把上面的代码添加到WordPress当前使用主题的模板函数(默认为:func

这样,我们下次编辑发布文章添加外部链接时,就不用打开“在新窗口打开”的按钮了,代码会自动帮我们在链接中添加target=”_blank”与rel=”nofollow”两个属性的。

WordPress站外链接自动添加target=”_blank”与rel=”nofollow”属性方法
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开USDT(trc-20)扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

Ts:本站所有内容均为互联网收集整理和网友上传。仅限于学习研究,请必须在24小时内删除。否则由此引发的法律纠纷及连带责任本站概不承担。

如侵犯到您的合法权益,请联系我们删除侵权资源!

分享驿站 技术文章 WordPress站外链接自动添加target=”_blank”与rel=”nofollow”属性方法 https://www.fxe.cc/1460.html

常见问题
  • 如何遇到网站源码不会安装,可以尝试搜索“程序名称 教程”,如dedecms 教程。 也可以查看 网站安装常见问题总结。
查看详情
  • 由于下载服务的特殊性,一旦您购买使用了下载服务,就不接受退款申请。详情请参考《分享驿站服务》条例。
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务