I just did an action on the query using pre_get_posts
and it didn’t work. When I removed the $query->is_main_query()
it did work.
So, how do you know that what is the main query. I know there is the function is_main_query
. What I am asking is there a way to tell which one you are looking at? How does WordPress know which one is the main query? If you have three or four going for different reasons such as categories, post types, pages. which is the main?
WP_Query->is_main_query()
method source (which function of same name calls) is very short and simple:The main query is the query that is stored in
$wp_the_query
global. But what is that global? When WP sets up main query it stores it in two places:$wp_the_query
and$wp_query
. Latter is more known because that variable is what you commonly use to work with main query and whatquery_posts()
changes.However
query_posts()
works like this:It break link between
$wp_query
and$wp_the_query
. And the reverse can be performend bywp_reset_query()
to re-establish that:So main query is the one that WP set up during core load.
It is typically what
$wp_query
holds, unless it was modified not to be main query anymore.