WordPress 站点中所有的外链在新窗口中打开,并且自动添加 NOFOLLOW 属性,有利于 SEO。
/** * 外链网址 */ function externalLink( $content ) { $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>"; if ( preg_match_all( "/$regexp/siU", $content, $matches, PREG_SET_ORDER ) ) { if ( ! empty( $matches ) ) { $site = get_option( 'siteurl' ); for ( $i=0; $i < count( $matches ); $i++ ) { $new = $matches[$i][0]; $old = $matches[$i][0]; $url = $matches[$i][0]; $noFollow = ''; $pattern = '/target\s*=\s*"\s*_blank\s*"/'; preg_match( $pattern, $old, $match, PREG_OFFSET_CAPTURE ); if ( count( $match ) < 1 ) $noFollow .= ' target="_blank" '; $pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/'; preg_match( $pattern, $old, $match, PREG_OFFSET_CAPTURE ); if ( count( $match ) < 1 ) $noFollow .= ' rel="nofollow" '; $pos = strpos( $url, $site ); if ( $pos === false ) { $new = rtrim ( $new, '>' ); $new .= $noFollow . '>'; $content = str_replace( $old, $new, $content ); } } } } $content = str_replace( ']]>', ']]>', $content ); return $content; }
add_filter( 'the_content', 'externalLink' );
还没有任何评论!