WordPress文章中的URL自动加a标签、nofollow、_blank

WordPress文章默认需要给链接插入连接才可以生成超链接,非常繁琐,现在只需几行代码,就有可以自动给文章中的所有连接添加a标签,并且加上nofollow和_blank属性,让连接自动在新窗口打开并且不传递权重。

效果:

WordPress文章中的URL自动加a标签、nofollow、_blank(1)-私域知识

 

代码:修改主题的functions.php文件,在最后加入:

// 文章页面链接添加nofollow标签并在新窗口打开
add_filter('the_content', 'make_clickable');
function autolinkraaynk( $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;
}
add_filter( 'the_content', 'autolinkraaynk');

 

1、订阅phpwc( 戳我关注公众号) 。

2、发现违法/侵权内容请点击 页面投诉 反馈。

3、虚拟产品售出不退,详见:《网站协议》

(0)

相关推荐

联系客服
公众号
公众号
留言交流
返回顶部