How to know which one is the main query?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

WP_Query->is_main_query() method source (which function of same name calls) is very short and simple:

function is_main_query() {
    global $wp_the_query;
    return $wp_the_query === $this;
}

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 what query_posts() changes.

However query_posts() works like this:

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

It break link between $wp_query and $wp_the_query. And the reverse can be performend by wp_reset_query() to re-establish that:

function wp_reset_query() {
    $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
    wp_reset_postdata();
}

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x