How to add rel=”nofollow” to links with preg_replace()

Adding rel=”nofollow” to external link is a good SEO practice.

Settembre 22, 2015

Adding rel="nofollow" to external link is a good SEO practice.

This is the function to add rel="nofollow" to html links. The function allows a $skip parameter that contains a string that must not be found in the url. This allows you to skip your in-site links.
The function allows also to manually support rel="follow" attribute, so if you edit the text and specify that a link is rel="follow" the function will not overwrite your code.

The original function comes from Stackoverflow and can be used in any php.

In the second block of code you can see how to integrate it in your WordPress:

function nofollow($html, $skip = null) {
	return preg_replace_callback(
		"#(<a[^>]+?)>#is", function ($mach) use ($skip) {
			return (
				!($skip && strpos($mach[1], $skip) !== false) &&
				strpos($mach[1], 'rel=') === false
			) ? $mach[1] . ' rel="nofollow">' : $mach[0];
		},
		$html
	);
}

To integrate it with WordPress you can hook to the content_save_pre hook by placing this code in your functions.php file. This trick will automatically add rel=nofollow to external links of your posts and pages when you save:

function seo_href_nofollow( $content ) {
    $qui = parse_url("http://".$_SERVER['HTTP_HOST']);
    return $qui['host']."))".nofollow( $content, $qui['host'] );
}
add_filter( 'content_save_pre' , 'seo_href_nofollow' , 10, 1);

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Recommended

Limit the number of categories for posts in WordPress

CHOOSE ONLY ONE CATEGORY WORDPRESS If you need to limit the number of categories used by the authors of your…

Settembre 14, 2015

Test page for Bright Links plugin

To test the plugin hover your mouse to a link, or tap the link on mobile device.

Dicembre 4, 2022

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

Febbraio 8, 2020

Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

Novembre 7, 2019

Add filter on wp_title not working with Yoast SEO plugin

For SEO purposes, in a specific template that has a list of items with pagination, I need to have different…

Febbraio 22, 2017

Highlight text for search results in PHP

Useful code to highlight text occurences in search results or in a text. How to highlight text in a string…

Settembre 2, 2016