Useful 'hack' for Amazon (and other) affiliates - Nofollow & Open in New Tab Automatically

Joined
Oct 20, 2014
Messages
128
Likes
145
Degree
1
#1
Hey,

just wanted to leave this script here in case someone finds adding nofollow and target blank attributes to affiliate links time-consuming and frustrating.

This script will automatically make all your outbound links open in a new window + all your Amazon affiliate links will automatically be labeled as nofollow. You can just paste the affiliate link in your content and everything will be handled for you.

Add this to your functions.php file:

Code:
function cdx_handel_external_links() {
    ?>
<script type="text/javascript">
( function( $ ) {

    $("a[href^=http]").click(function(){
      if(this.href.indexOf(location.hostname) == -1) {
         $(this).attr({
            target: "_blank"
         });
      }
    })

   //Add Nofollow
   $("a").each(function(){
    if(this.href.indexOf('amazon.com') >0 ){
        $(this).attr({
            rel: "nofollow"
         });
    }
   });

} )( jQuery );
</script>
   <?php
}
add_filter( 'wp_footer', 'cdx_handel_external_links', 999);
 
Last edited:
Joined
Sep 17, 2014
Messages
406
Likes
257
Degree
1
#2
I was looking at something like this yesterday but filtering the_content() through PHP on Wordpress.

Remember though, this code you posted is applied after the page has loaded. It's not in the source code itself. So depending on if Google is executing your Javascript before it wonders if your affiliate links are nofollow or not, it still may not be the best fix. PHP would change the source code itself.

You could also do a MySQL search and replace in the database to add rel=nofollow and target=_blank