Own your WordPress loop with wp_query
The WordPress loop is arguably the heart of any WP powered site. With all this power at its fingertips, it obviously has some serious customization potential. I’m going to explain a couple of ways here of how you can fully use the potential of your WP CMS’s loop to display custom content anywhere on your site. Get ready to own your WP Loop!
Remembering that content is king, I always recommend to my clients that they have a blog of some sort: a style blog, Pokerblog, Tech blog – whatever it is they do, they need a blog. Thus somewhere in your custom WP theme, you’re going to want to display maybe the latest 2 or 3 articles from their blog. Usually, you could just use
query_posts() to bring in posts from a specific category.
However, I’ve found in the past that if I use this method before the normal loop for the page’s content, it messes with the functionality of the main loop because of issues with
rewind_posts() and such.
To altogether avoid this issue, it’ll be best if you get used to making your own WP query.
Making your loop
Before looping, you need to tell WordPress what to loop through. So firstly, setup your query.
<? $recentPosts = new WP_Query(); $recentPosts->query('showposts=5'); ?>
Then you can join it up with a loop to process the information that your query finds.
<? while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> <!-- LOOP STUFF HERE --> <?php endwhile; ?>
So when you add it all together:
<?php $recentPosts = new WP_Query(); $recentPosts->query('showposts=5'); while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> <!-- LOOP STUFF HERE --> <?php endwhile; ?>
The query itself can have many different arguments to help you filter down to exactly what you’re looking for. For example:
cat=3– specify the category that you want to display. If you have more posts that you want to include than exclude, then it might be easier to just filter out the ones you don’t want to see by using:
cat=-1, -2, -3etc
showposts=3– specify how many posts you want to show
orderby=name– determine how you want your results to be ordered by: author, date, category, id, title, modified, parent and rand. orderby=rand is a great means of having a news area that displays a random news article from the archives.
year=2004– display posts from only a specific year
You can string a whole bunch of these arguments together like so:
<? query_posts('cat=3,4,5&showposts=10&orderby=date'); ?>
With a little imagination, your query can retrieve any number of configurable results.