wp_rel_nofollow()WP 1.5.0

Adds rel nofollow string to all HTML A elements in content.

No Hooks.

Return

String. Converted content.

Usage

wp_rel_nofollow( $text );
$text(string) (required)
Content that may contain HTML A elements.

Examples

0

#1 An example of adding the rel="nofollow" attribute to all links in the text

$text = 'Man needs laughter like a flower needs sunlight.
If it happened that laughter became extinct, humanity would become
would have gone to a zoo or an angelic society - became boring,
sullen and frozen in majestic indifference.
Read a novel by James Crews:
<a href="http://flibusta.net/b/162259">Sold Laughter</a>';

$text = wp_rel_nofollow( $text );

echo $text;

// The link in this text will turn into:
// <a href="http://flibusta.net/b/162259" rel="nofollow">Sold Laughter</a>.
0

#2 Add a nofollow attribute to all external links in the content

add_filter( 'the_content', 'wp_posts_nofollow' );

function wp_posts_nofollow( $content ){
	return stripslashes( wp_rel_nofollow( $content ) );
}
0

#3 Improve the handling of external links. [auto-translate]

Let's close external links in the content from indexing and add target="_blank".

add_filter( 'the_content', 'external_links_sanitizer' );

function external_links_sanitizer( $content ){

	$content = wp_unslash( wp_rel_nofollow( $content ) );
	$content = str_replace( 'rel="nofollow"', 'target="_blank" rel="nofollow noindex noopener"', $content );

	return $content;
}

Changelog

Since 1.5.0 Introduced.

wp_rel_nofollow() code WP 6.4.3

function wp_rel_nofollow( $text ) {
	// This is a pre-save filter, so text is already escaped.
	$text = stripslashes( $text );
	$text = preg_replace_callback(
		'|<a (.+?)>|i',
		static function ( $matches ) {
			return wp_rel_callback( $matches, 'nofollow' );
		},
		$text
	);
	return wp_slash( $text );
}