How to use query_posts properly

in WordPress Tutorials

The WordPress function query_posts is an incredibly useful and easy-to-use method for altering the results of The Loop. The Loop, as you may know, is the method that WordPress uses to gather up the information about the post or posts on the page. In this case, I use post in the generic sense of “content” — not in the WordPress definition of post. The reason, of course, is that WordPress pages and even custom post types also use The Loop to display their “main” content.

The query_posts function is a one-line bit of code that you can put in your code above The Loop. While you don’t necessarily have to put query_posts directly above The Loop, for clarity and sanity purposes, we definitely recommend making any query_posts call in the line immediately prior to The Loop. This will make it much easier to debug any issues in the immediate or far future.

Once you’ve added query_posts, the result is that your loop will return what essentially amount to a filtered version of what would have shown up in The Loop regardless. For instance, if you only want posts from a certain category, you could add a line of code like the following:

query_posts( ‘cat=10′ );

This will result in the loop only showing results from the category with the id of 10. You might be asking, where do I get that category id? Two places. First, you can dig around the database for it. Second, and much easier, is simply to look at the URL in the WordPress Admin when you’re editing/adding categories. So if you simply go to the categories area (currently under the “Posts” menu) and then look at the URL for any category, you’ll see a number in the query string parameters. Just take that number and put it in the place of the 10 in the example above. And that’s it, it’s that simple!

Comments Closed