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