wordpress文章内链接自动新窗口打开以及添加nofollow属性

今天在使用邓总的跳转页插件时遇到了问题,如下图:

邓总也及时的给出了解答,但是我个人感觉我还是需要跳转页的功能而且noreferrer属性目前对我来说不是特别重要,至少我没感受到这个属性的存在感。

不过既然有了邓总的解答那问题就比较好解决了,只要把链接里的rel=”noreferrer noopener”属性去掉即可。

可以用下边这段代码给wp所有超链接添加一个target=”_blank以及rel=”nofollow”属性,这两个目前都是我必须的,正好可以解决眼前的问题。

//WordPress 移除链接中的 rel="noreferrer noopener" 属性
    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;
    }

相关推荐

暂无评论