Automatically add rel="sponsored nofollow" to affiliate links in your posts, as Google asks, using WordPress's HTML API.
add_filter( 'the_content', function ( string $content ): string {
if ( ! str_contains( $content, '<a ' ) ) {
return $content;
}
// Parts of URLs that mean "this is an affiliate link".
$sponsored = [ 'amzn.to', 'amazon.com/', 'shareasale.com', '/go/', '?ref=' ];
$html = new WP_HTML_Tag_Processor( $content );
while ( $html->next_tag( 'a' ) ) {
$href = (string) $html->get_attribute( 'href' );
foreach ( $sponsored as $needle ) {
if ( '' !== $href && str_contains( $href, $needle ) ) {
$rel = array_filter( explode( ' ', (string) $html->get_attribute( 'rel' ) ) );
$html->set_attribute( 'rel', implode( ' ', array_unique( array_merge( $rel, [ 'sponsored', 'nofollow' ] ) ) ) );
break;
}
}
}
return $html->get_updated_html();
}, 20 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Google asks sites to mark paid and affiliate links with rel="sponsored". Doing it by hand on every link is easy to forget. This snippet does it automatically when posts are displayed.
WP_HTML_Tag_Processor is WordPress’s built-in HTML parser. It walks through every link in the post content and, if the address contains one of your patterns, such as an Amazon short link or your own /go/ redirect folder, adds sponsored and nofollow to its rel attribute, keeping any values already there.
Using the HTML API is safer than regular expressions: it handles attributes in any order and quoting style, and never breaks the markup.
Add an Amazon link to a post and view the source. The link should have rel="sponsored nofollow".