WP_Query, conditional tags, pre_get_posts, get_posts, query_posts: when to use what

by , July 2, 2012

There are various methods available to interact with the WordPress query and it can get confusing to identify which one is best for a particular purpose. Here are the conclusions I drew from diving in the WordPress Codex,  in the form of a (hopefully) simple table. Follow the links to the Codex for technical details – or post your questions below!

What you want to do Functions/tags to use Notes and warnings
Getting information about the current query/loop The WP_Query object Very rarely needed. Make sure you’ve run out of options with conditional tags and tags available in the loop
Conditional tags Particularly useful in plugin development to limit actions to certain types of pages
Modifying the main query/loop the pre_get_post action Whish I had found about that sooner!!!
Requires a good knowledge of the structure of the $query object
the query_posts function Usage discouraged
Messes up with pagination, see fix here
Generating a secondary loop (e.g. post listing in a widget) the get_posts function Best suited tool for this purpose!
new instance of WP_Query Just use get_posts!

Comments (0)

Be the first to comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

MAJ tweets