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.
- To display a quote from a random article in the sidebar of our blog.
- 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.
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. Check it out -
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; ?>
With that, we’re done. Like the way I’ve laid this out? Please do leave a comment.