Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.