Ad Rotating in WordPress

OK, so here’s the deal, I wanted to add some affiliate adverts to my sidebar and get them to rotate them every time the page is refreshed or when the visitor goes to a new page. However, I had some conditions:

  • I didn’t want to use a plugin (too many plugins can be a bad thing)
  • I wanted to keep it modular so I didn’t want it hard coded into the page.

Useful PHP

So here’s what I did, I went and found some code to allow you to put PHP code directly into a Text widget (there are plugins that do this but remember I’m wanting to do this without plugins)

add_filter('widget_text', 'php_text', 99);

function php_text($text) {
if (strpos($text, '<' . '?') !== false) {
ob_start();
eval('?' . '>' . $text);
$text = ob_get_contents();
ob_end_clean();
}
return $text;
}

Source

This code needs to be added to your functions.php file.

Then I needed to create a simple randomiser so that the adverts would change on refresh.

Looks complicated, but isn’t really

';

}

elseif($rand > 20 && $rand <= 40 )

{

echo '';

}

elseif($rand >40 && $rand <=60)

{

echo '';

}

elseif($rand >60 && $rand <=80)

{

echo '';

}

else

{

echo '';

}

?>

In English this does the following:

Randomly choose a number between 1 and 100

If its between 1 and 20 display image 1

If its between 21 and 40 display image 2

If its between 41 and 60 display image 3

If its between 61 and 80 display image 4

If its anything else display image 5

With this, there is a 1 in 5 chance of an individual image to appear. If you add or take away images you will need to amend the percentages (or if you just want an advert to appear more or less often).

Here is a quick explanation of the characters before each number:

> Greater than – so if its > 20 its 21 or higher

=> Greater than or equal to – so if its => 20 then it means 20 or higher

< Less than

<= Less than or equal to

= Equals

Now most sellers will give an affiliate an over all banner link that you would just need to put between the two ‘ ‘ after the echo. However, some decide that they wont do this and just give you an affiliate code and separate banner, or even worse just a code!

What I tend to do in this situations, is either find or create an image and upload it to the /images folder via ftp and fill in the details as per the code above.

Once all the code is to your liking with the right affiliate links and the right percentiles, then copy it all and paste it into a text widget in your sidebar.

What about Google AdSense?

Well if you want to put Google AdSense in to the mix you have two options.

  • You can just put the AdSense code directly into a Text Widget and let it do its thing
  • You can insert the AdSense code into the ‘ ‘ after an echo and have the AdSense come up like the other ads.

So that is a relatively easy way to place a rotating advert on your site, without using a plugin or hard coding.