WP_Query, conditional tags, pre_get_posts, get_posts, query_posts: when to use what
by Marie, 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! |
Category: Web pro stuff, Wordpress development | Tags: wordpress loop, wordpress query |

Be the first to comment!