Halloween Sale 15% off Ends in See the plans
PHP

Don't Send Referrer Information to Other Sites

Adds rel="noreferrer" to links in your content that point to other websites, so the sites you link to do not learn which page the visitor came from.

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

Code

// Domains that should still receive the referrer.
$wpide_referrer_allowed = array( 'amazon.com' );

add_filter( 'the_content', function ( $content ) use ( $wpide_referrer_allowed ) {
    if ( false === stripos( $content, '<a' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
        return $content;
    }

    $own  = wp_parse_url( home_url(), PHP_URL_HOST );
    $tags = new WP_HTML_Tag_Processor( $content );

    while ( $tags->next_tag( 'a' ) ) {
        $host = wp_parse_url( (string) $tags->get_attribute( 'href' ), PHP_URL_HOST );

        if ( ! $host || $host === $own ) {
            continue;
        }

        foreach ( $wpide_referrer_allowed as $domain ) {
            if ( $host === $domain || substr( $host, -strlen( '.' . $domain ) ) === '.' . $domain ) {
                continue 2;
            }
        }

        $rel = preg_split( '/\s+/', trim( (string) $tags->get_attribute( 'rel' ) ), -1, PREG_SPLIT_NO_EMPTY );
        $rel = array_unique( array_merge( $rel, array( 'noreferrer', 'noopener' ) ) );
        $tags->set_attribute( 'rel', implode( ' ', $rel ) );
    }

    return $tags->get_updated_html();
}, 20 );

Notes

Affiliate programs that rely on the referrer to credit you may stop working; add their domains to $wpide_referrer_allowed.

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.