目前我正在使用以下代码添加rel=nofollow
和target=_blank
我的网站内容的所有外部链接,但我希望这样only 在贡献者帖子上。也就是说,作者及以上的帖子没有重写规则。
<?php
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;
}
最合适的回答,由SO网友:kaiser 整理而成
有author_can()
为此:
add_action( \'loop_start\', \'wpse105294_nofollow_author\' );
function wpse105294_nofollow_author()
{
! author_can( $GLOBALS[\'post\']->ID, \'edit_others_posts\' )
AND add_filter( \'the_content\', \'cn_nf_url_parse\');
}
因此,您只为作者和其他无法
edit_others_posts
. 默认情况下,这是
Subscriber
和
Author
. 有关更多信息,请查看
Codex article about Roles and Capabilities.
编辑
因为我最近用PHP HTML DOM解析器做了一些工作,所以我认为使用这个可能更好。为了方便起见,代码主要取自
@Alex answer on SO.
add_filter( \'the_content\', \'cn_nf_url_parse\');
function wpse_105294_Content_Parser( $content )
{
$dom = new DOMDocument;
$dom->loadHTML( $content );
// DOMXPath() might be just too much
$anchors = $dom->getElementByTagName( \'a\' );
foreach ( $anchors as $a )
{
if (
! $a->hasAttribute( \'rel\' )
OR \'\' === ( $rel = trim( $a->getAttribute( \'rel\' ) ) )
)
continue;
$rel = preg_split( \'/\\s+/\', $rel );
if ( in_array( \'nofollow\', $rel ) )
continue;
$rel[] = \'nofollow\';
$anchor->setAttribute( \'rel\', implode( \' \', $rel ) );
}
$html = \'\';
// Remove `html\\body` before returning
foreach ( $dom->getElementsByTagName( \'body\' )->item(0)->childNodes as $el )
$html .= $dom->saveXML( $el, LIBXML_NOEMPTYTAG );
return $html;
}