Display Random Adverts in WordPress with Custom Fields
Posted on 15. Jul, 2009 by Alex Denning in Archive
Whilst building the exciting new version of Nometech (to be launched very, very soon!) [update - it has launched, this is it!], I needed a way of displaying a random 300×250 advert in the sidebar. After a bit of Google-ing to no avail, something came to me – ‘why not use custom fields?!‘. Really, why not! In this post I’ll show you how to display a random advert in WordPress using custom fields and a couple of posts you’ve already written.
First thing to do is to upload the adverts you want to display to your theme’s folder /images. With that done, assuming you have three adverts you want to rotate, find three posts and add them to a category ‘Adverts’. Then, in each of the three posts, add a different advert to the custom field ‘Advert’. The image below shows what I mean – add the HTML link and image:
With that done to all three posts, now comes the code, which you can add where-ever to your theme, but I’d suggest in the sidebar.php file.
[php]<?php $my_query = new WP_Query(‘category_name=Adverts&showposts=1&orderby=rand’); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php echo get_post_meta($post->ID, "Advert", true); ?>
<?php endwhile; ?>[/php]
And that’s that. Any queries leave a comment below.

Enjoyed the post? We'll see you on Twitter or in your RSS reader!

WPShout is hosted by the fine folks at WPWebHost.
You can get exactly the same hosting as WPShout has for $7.95/month with WPWebHost's Freedom Plan.
Plus get 30% off the Freedom Plan with the code WPSHOUT.
Alex Denning is the founder of WPShout. A WordPress developer from London, Alex is a keen musician and freelance writer and developer.
You can find Alex on Twitter.
4 Responses to “Display Random Adverts in WordPress with Custom Fields”
Trackbacks/Pingbacks
[...] you may know from various hints I’ve been dropping recently, Nometech has been going through a little redesign and relaunch, [...]





Rarst
15. Jul, 2009
Why not write tiny function (possibly with shortcode on top) that will return one of three images randomly and use it wherever needed?
Using custom field for storing information completely unrelated to post and running query to get it seems roundabout.
NickG
15. Jul, 2009
Better yet, why not just use this plugin?
http://wordpress.org/extend/plugins/random-ads/
Alex Denning
16. Jul, 2009
@Rarst @NickG sure, not the best way to display a random ad, but it's the principle and shows what can be done with custom fields!