Create an ads rotator with php for wordpress

November 27, 2008 · Print This Article

If you wanted to be able to display a group of X image ads in your theme. Nothing hard with this. But, you also wanted to be able to add as many ads as you’d like. Nevermind how many ads you added, only 4 must be displayed at the same time.

Then how to do that?

We came up with the solution of a rotator which will take X items, sort them randomly and pick up 4 of them for being displayed.

To achieve this, We will create a php array which will contains another array for each item, with infos as such as title, image and url.

Each item will be displayed with a html unordered list, which will allow us to use css to control the display and give our item the look and feel we want.

Here’s the code used. You just have to paste it where you want the ad rotator to appear. Or even better, you can create a function with it.


<?php
$ads = array(array("title"=>"ad1",
"img" =>"ad1.jpg",
"url" =>"ad1.html",),

array("title"=>"ad2",
"img" =>"ad2.jpg",
"url" =>"ad2.html",),

array("title"=>"ad3",
"img" =>"ad3.jpg",
"url" =>"ad3.html",),

array("title"=>"ad4",
"img" =>"ad4.jpg",
"url" =>"ad4.html",)
);

$rand_keys = array_rand($ads, 4);

echo '<a href="'.$themes[$rand_keys[0]][url].'" target="blank"><img src="'.$themes[$rand_keys[0]][img].'" alt="" /></a>';
echo '<a href="'.$themes[$rand_keys[1]][url].'" target="blank"><img src="'.$themes[$rand_keys[1]][img].'" alt="" /></a>';
echo '<a href="'.$themes[$rand_keys[2]][url].'" target="blank"><img src="'.$themes[$rand_keys[2]][img].'" alt="" /></a>';
echo '<a href="'.$themes[$rand_keys[3]][url].'" target="blank"><img src="'.$themes[$rand_keys[3]][img].'" alt="" /></a>';

?>

You can also use foreach loop to do same.


<?php
$ads = array(array("title"=>"ad1",
"img" =>"ad1.jpg",
"url" =>"ad1.html",),

array("title"=>"ad2",
"img" =>"ad2.jpg",
"url" =>"ad2.html",),

array("title"=>"ad3",
"img" =>"ad3.jpg",
"url" =>"ad3.html",),

array("title"=>"ad4",
"img" =>"ad4.jpg",
"url" =>"ad4.html",)
);

shuffle($ads);
$ads = array($ads[0],$ads[1],$ads[2],$ads[3]);
foreach($ads as $ad){
?>
<a href="<?php=$ad["url"]?>" target="blank"><img src="<?php =$ad["img"]?>" alt="<?php =$ad["title"]?>" border="0"/></a>
<?php
}
?>

Adding a new item to the rotator is very easy. You just have to add a new ellement to the $ad array:


array( title => "Item title",
img => "image url",
url => "url",
),

You can use it for many others usages, as such as displaying 125*125px ads, or create a rotating blogroll for your WordPress blog.


Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.