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

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

September 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

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

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…

September 14, 2015

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…

February 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…

September 2, 2016

Clean up and optimize WordPress head tag

If you need to know how to remove RSS Feed URL’s from page head or how to remove post relational…

December 11, 2015

Social buttons: the fastest way for WordPress, without plugins

NOTE: the code in this post is written for WordPress but you can easily translate it in any language. You’re here…

September 15, 2015

Optimize WordPress, a long list of tips

In the above image you can see your WordPress before reading this post, and after the optimizations you will make…