Difference between new WP_query() and query_posts()

A question about efficiency. What is the difference between using wp_query($args) and $query = new WP_Query($args)? Is there any difference in efficiency / the number of SQL queries? Is one always better than the other, or are there cases in which one style is preferred?

For example, if I want a complex page with 3 columns based on category, how are the following two examples different?

Read More
$query = new WP_Query("category_name=Issue 1")
while ($query->have_posts())....

vs.

rewind_posts()
query_posts("category_name=Issue 1")
while(have_posts())...

Related posts

Leave a Reply

4 comments

  1. Nothing.

    One just calls the other, this is from the WP source.

    function query_posts($query) {
            $GLOBALS['wp_query'] = new WP_Query();
            return $GLOBALS['wp_query']->query($query);
    }
    

    God, I love WP, its soooo slick. Fail.

  2. Use WP_Query.

    From the WordPress query_posts Function Reference:

    It should be noted that using this to replace the main query on a page
    can increase page loading times, in worst case scenarios more than
    doubling the amount of work needed or more
    . While easy to use, the
    function is also prone to confusion and problems later on. See the
    note further below on caveats for details.

    For general post queries, use WP_Query or get_posts

    It is strongly recommended that you use the pre_get_posts filter
    instead, and alter the main query by checking is_main_query

    With WP_Query, you can run more than one query on a page. query_posts just replaces the main loop with a custom query. As the documentation states, there are better ways of modifying the main loop than using query_posts.

  3. WP_Query is a superset of query_posts() & get_posts() function. Both functions will call the WP_Query. But I have found following differences from internet.

    • query_posts() might be used in one and only case if you need to modify main query of page (for which there are better and more reliable methods to accomplish, over simplistic approach of this function). 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. Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose. Don’t use query_posts() ever;

    • 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.