How To: Display Quotes From A Random Post in WordPress

Whilst considering the best way to show off all the content effectively on WPShout, a thought occurred to me – why not have quotes from articles popping out on the sidebar? In the end I decided against the idea, but I thought I’d write it up for all to see. I’m writing this a bit differently – good, bad? Please do let me know.

 

Aim

  • To display a quote from a random article in the sidebar of our blog.

Hypothesis

  • Use of custom fields to pull data from posts. Preferably custom write panels to spice it up a bit.
  • Loop (preferably without replacing the loop already in use) to pull a random post and display custom field.

Method

First thing we’ve got to do is create the custom field with the quote from the article. Here there are two options. First is to just use the custom field and copy and paste the quote into it. Second option is to make things look a little nicer and use some custom write panels. This isn’t nearly as hard as it sounds and to prove the point, I’ve made a screencast which is exactly five minutes long in which I add custom write panels to the default theme.

As I’ve just proved, it’s easy to add these custom write panels and what I didn’t quite finish saying was that were you to save any content into your quote field, it’d then get saved as the custom field quote. We’re now ready to move onto part two.

Next we need some way of pulling this custom field and displaying it in the sidebar. The obvious answer is to use the loop and that’s true, although by doing that you replace the loop already in use which I don’t really want to do – if anyone has a better way of doing this please do leave a comment (code should be wrapped in <pre><code>pre and code</code></pre> tags). Pressing on with this method though, first we need a custom loop:

<?php
$quotes = new WP_Query();
$quotes->query('showposts=1&meta_key=Quote&orderby=rand');
while ($quotes->have_posts()) : $quotes->the_post(); ?>

<?php endwhile; ?>

Here we’re being very clever – we’re pulling a random single post with the custom field ‘Quote’. Of course, next we need to pull the custom field so the full loop looks like this:

<?php
$quotes = new WP_Query();
$quotes->query('showposts=1&meta_key=Quote&orderby=rand');
while ($quotes->have_posts()) : $quotes->the_post(); ?>

<?php echo get_post_meta($post->ID, "Quote", true); ?>

<?php endwhile; ?>

Conclusion

With that, we’re done. Like the way I’ve laid this out? Please do leave a comment.


3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
oomes
August 27, 2010 6:39 pm

Thanx, helped me out on something…..

Il meglio della settimana #35 | BigThink
October 24, 2009 10:35 am

[…] How to: Display quotes from a random post in WordPress Come mostrare nella sidebar una citazione da un post casuale . […]

Comment Name Violation
October 22, 2009 8:25 pm

thanks for this great post.