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.
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: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 usingquery_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.