Which one to use WP_Query vs query_posts() vs get_posts()?

There are several instances where we want to display content other than what WordPress displays at a particular page. There are three methods which you can use, but each of them is meant for a specific purpose, otherwise why would they have existed? Makes sense? Good!

Some tutorials use one, some other and many of them are in fact incorrect because they might seem to get the job done but in certain cases they cause side effects, such as modified global variables on which other functionality may rely.

The fight is in between using WP_Query or query_posts or get_posts. Rarst created a great chart to explain what is going on in the three approaches to make it easy to understand the working. which I totally recommend checking out.

wordpress query

Rarst explained the difference quite precisely as follows:

  • query_posts() should be used in one and only case if you need to modify main query of page. It sets a lot of global variables and will lead to obscure and horrible bugs if used in any other place and for any other purpose;
  • get_posts() is very similar in mechanics and accepts same arguments, but returns array of posts, doesn't modify global variables and is safe to use anywhere;
  • WP_Query class power both behind the scenes, but you can also create and work with own object of it. Bit more complex, less restrictions, also safe to use anywhere.
I want to stress that query_post() wrongfully overused in many tutorials around. It is one of the most widespread bad practices.

Next time you need to make WordPress to show content other than what it does by default, take care to choose the right method. If there is something that you don't understand in the chart, leave a comment here and I will happily explain. :)

Published by

Ashfame

Developer + Entrepreneur + Opensource fanatic. Love WordPress + Startups + Music + Adrenaline kick.

  • Pingback: Pagination approach using get_posts()()

  • http://sunriseweb.ca Brad Trivers

    Love the diagram – thanks for the comparison!

    Just wanted to get your opinion on where the “$wpdb->get_results($querystr);” method fits in.

    Specifically I’m interested to hear your opinion on what type of query is fastest. Seems to me that defining my own sql and then using $wpdb->get_results($sql) should be it since you can choose exactly what fields are needed. Does get_posts() always retrieve all fields for a post?