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.

Have you noticed WPShout loads super-fast? That's because the site is running on the super-amazing WPEngine hosting.

Fed up of shared hosts that don't work? Give them a try.

About the author

Hello, I'm Alex! WPShout is my collection of WordPress tutorials which I started 4 years ago, just before my 16th birthday. If you need someone to make you WordPress screencasts or documentation for your product or service, get in touch — I'll be able to help you out. You should also follow me on Twitter :)

4 Comments