1

I have a theme where I need multiple queries for each column. Is it better to modify the main query with pre_get_post and reset the loop or create a new query for each of my columns?

| improve this question | | | | |
1

I think that you are making some confusion between main query and secondary queries in Wordpress. Maybe read this can help you to better understand.

In short when you visit an url of your site, that url make wordpress fires a query on db: this is the main query.

Thanks to the action pre_get_post you can modify the main query, e.g. adding, removing or edit query vars before the query is runned on db.

But once the query fired, the only chance to recreate a query that you can call 'main' 1 (even if is not triggered by url) is use query_posts, but this practice is highly not recommended.

So if your question is: "Should I use new WP_Query instances for multiple queries or should I use multiple query_posts calls?"

The answer is, surely, new WP_Query instances.


1 You can call 'main' the query runned by query_posts, because the main query, is characterized from 2 aspects (besides the fact that normally is triggered by the url):

  1. It's an object (an instance of WP_Query more precisely) named $wp_query in the global scope. (You can access to it using global $wp_query;)
  2. You can cycle the posts handled by this query using the loop.

Once the query you obtain using query_posts have both these characteristics, it is fledged the main query, even if is not triggered by url.

| improve this answer | | | | |
  • Thank you, the link and this answer are very useful! But I think I don't understand something. There can be multiple queries considered as a main query? Because if I do a secondary query, it is an instance of WP_Query and I can cycle the posts with this query, so it has the same characteristics of a main query? – user25893 Sep 13 '13 at 3:27
  • 1
    @Maxwell you can loop the secondary query, but you have to use while($myquery->have_posts()) and not only while (have_posts()), see the difference? And then, the main query is accessible everywhere, using global $wp_query; the secondary query not, the are accessible via the variable that you assign to it, e.g. $my_query: if you assign the name $wp_query and put it in the global scope, you will breack a lot of things... – gmazzap Sep 13 '13 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy