# 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.

- Type: PHP
- Runs: Frontend only
- Category: [SEO](https://wpide.com/library/category/seo/)
- Tags: affiliate, sponsored, links
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/sponsored-affiliate-links/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Mark Affiliate Links as Sponsored" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
