Mark Affiliate Links as Sponsored
Adds rel="sponsored nofollow" to links that go to your affiliate programs or cloaked /go/ links, as search engines ask for paid links.
Opens WPIDE on
Code
// Affiliate domains (subdomains included).
$wpide_affiliate_domains = array( 'amzn.to', 'amazon.com', 'shareasale.com' );
// Paths on your own site used for cloaked affiliate links.
$wpide_affiliate_paths = array( '/go/', '/recommends/' );
add_filter( 'the_content', function ( $content ) use ( $wpide_affiliate_domains, $wpide_affiliate_paths ) {
if ( false === stripos( $content, '<a ' ) ) {
return $content;
}
$own = strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) );
$result = preg_replace_callback( '/<a\s[^>]*href=(["\'])([^"\']+)\1[^>]*>/i', function ( $m ) use ( $own, $wpide_affiliate_domains, $wpide_affiliate_paths ) {
$url = $m[2];
$host = strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) );
$path = (string) wp_parse_url( $url, PHP_URL_PATH );
$hit = false;
foreach ( $wpide_affiliate_domains as $domain ) {
if ( $host && ( $host === $domain || substr( $host, -strlen( '.' . $domain ) ) === '.' . $domain ) ) {
$hit = true;
}
}
if ( ! $hit && ( ! $host || $host === $own ) ) {
foreach ( $wpide_affiliate_paths as $prefix ) {
if ( 0 === strpos( $path, $prefix ) ) {
$hit = true;
}
}
}
if ( ! $hit ) {
return $m[0];
}
$tag = preg_replace( '/\srel=(["\'])[^"\']*\1/i', '', $m[0] );
return substr( $tag, 0, -1 ) . ' rel="sponsored nofollow noopener">';
}, $content );
return null === $result ? $content : $result;
}, 21 );
Notes
List affiliate domains and any local link prefixes, such as /go/ or /recommends/, at the top.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.