新WP_query()和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?

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

vs.

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

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.

There's an array of decent answers here: https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts

You're better off going with the first option as a rule of thumb. With query_posts your essentially create a WP_Query and assigning it to the global wp_query. This can be seriously problematic if you ever forget to reset your posts. Hope that all helps explain it!

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.

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.