Display Random Adverts in WordPress with Custom Fields

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:

customfields

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.


4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Nometech relaunches! Introducing WPShout.com | WPShout.com
July 18, 2009 11:05 am

[…] you may know from various hints I’ve been dropping recently, Nometech has been going through a little redesign and relaunch, […]

Alex Denning
July 16, 2009 1:01 pm

@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!

NickG
July 15, 2009 8:37 pm

Better yet, why not just use this plugin?

http://wordpress.org/extend/plugins/random-ads/

Rarst
July 15, 2009 7:28 pm

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. 🙂