WordPress: aggiungere un nofollow ai link esterni

Come aggiungere un nofollow automatico ai link esterni in WordPress.

WordPress di Gabriele Romanato

Alcuni giorni fa un mio lettore mi aveva rivolto una domanda interessante: come posso aggiungere un nofollow ai link esterni all'interno dei miei post e delle mie pagine di WordPress? Vediamo insieme questa soluzione.

Possiamo aggiungere il seguente codice al file functions.php:


add_filter('the_content', 'nofollow');

function nofollow($content) {
	$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
	$home = get_bloginfo('site_url');
	if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
		foreach($matches as $match) {
			// $match[2] = URL
			// $match[3] = Testo del link
			$address = $match[2];
			$text = $match[3];
			if(stristr($address, $home) === false) {
				$find = '<a href="' . $address . '">' . $text . '</a>';
				$replace = '<a href="' . $address . '" rel="nofollow">' . $text . '</a>';
				$content = str_replace($find, $replace, $content);
			}
		}
	}
	return $content;
}

L'espressione regolare usata prende in considerazione i link HTML privi di attributi. Qualora i vostri link presentassero degli attributi, dovete modificare l'espressione regolare.