SEO PHP Intermediate

Mark Affiliate Links as Sponsored

Automatically add rel="sponsored nofollow" to affiliate links in your posts, as Google asks, using WordPress's HTML API.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 22 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • The content in the database isn’t changed; links are marked as the page is shown.
  • Many countries also require a visible disclosure near affiliate links. This snippet doesn’t add one.

How to test it

Add an Amazon link to a post and view the source. The link should have rel="sponsored nofollow".

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only