Quick WordPress tip: Automatically replace words by affiliate links

Some months ago I wrote a post about a plugin called Ninja Affiliate. The plugin allowed you to automatically replace words by an affiliate link. It’s a cool plugin (I use it on my blog) but it’s not free. Some reders suggested free plugins, such as SEO Smart Links, that can do the same job.

Today, I’d like to show you a simple piece of code that can replace words of your choice by an affiliate link. It’s simple, it’s free, and it works. I do not give you as much control as the plugins does, but in most cases this code should fit your needs.

Simply paste the code below into your functions.php file. Don’t forget to enter your words/links as shown in the example code.

function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'thesis' => '<a href="http://mysite.com/myafflink">thesis</a>',
        'studiopress' => '<a href="http://mysite.com/myafflink">studiopress</a>'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}

add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');

Have fun! This code is courtesy of Kevin Chard from WpSnipp, so big thanks to him!

Published on March 14th, 2011 by Jean-Baptiste Jung

Leave a Reply