wp_rel_nofollow()
Adds rel="nofollow" to all <a> elements in the passed text. Internal links are skipped.
If a link is internal (points to a page on the current site), the nofollow attribute will not be added.
See also:
Uses: wp_rel_callback()
No Hooks.
Returns
String. Formatted content.
Usage
wp_rel_nofollow( $text );
- $text(string) (required)
- Content that may contain HTML A tags.
Examples
#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>.
#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 ) );
} #3 Improve the handling of external links.
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() wp rel nofollow code WP 6.8.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 );
}