Display Random Adverts in WordPress with Custom Fields

Posted on 15. Jul, 2009 by Alex Denning in Quick Tips

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.

No related posts.

Tags:

Follow on Twitter! Subscribe!
Alex's Gravatar

Alex Denning is the founder of WPShout. A WordPress developer from London, Alex co-founded WPShift at the start of 2010 where he sells awesome WordPress themes.

You can find Alex on Twitter and at AlexDenning.com.

4 Responses to “Display Random Adverts in WordPress with Custom Fields”

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

    Reply to this comment
  2. NickG

    15. Jul, 2009

    Better yet, why not just use this plugin?

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

    Reply to this comment
  3. 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!

    Reply to this comment

Trackbacks/Pingbacks

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

Leave a Reply

Please use your real name when commenting. Wrap code in <code> tags and make sure HTML is encoded. You can use regular HTML like <a href="... etc.

Get yours questions answered quicker

If you're using this post for paid work and have a question of any complexity then please ask at WPQuestions where you'll get a prompt response.