What is “main query”?

The question:

Possible Duplicate:
How to know which one is the main query?

I’m curious to know what is the so called “main query”?

What I have is two queries on front page.

if (have_posts()) : while (have_posts()) : the_post();
    // do the main loop
endwhile; endif;

$posts = new WP_Query(array('post_type' => 'some_other_post_type'));
while ($posts->have_posts()) : $posts->the_post();
    // do the secondary loop
    // but still operating with the some_post_type
endwhile; wp_reset_postdata();

And what I want is just to modify the main query to my custom post type for efficiency.

add_action( 'pre_get_posts', 'some_name');
function some_name($query) {
    if (is_front_page() && is_main_query()) {
        $query->set( 'post_type', 'some_post_type' );
        return;
    }
}

What I thought is that condition in that hook will be true only for the first loop, but it appears that any new WP_Query is passing through it.

Can you explain me, please, what is “main query” and what is not?

PS: I’ve found almost a similar question with the solution to vary the queries in pre_get_post hook by custom query vars.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Your filter has a bug in it, namely when you call is_main_query, you’re not checking if the passed query is the main query, your checking if the currently active query is the main query, which will always be true.

So instead try this:

add_action( 'pre_get_posts', 'modify_frontpage_main_query' );
function modify_frontpage_main_query( WP_Query $query ) : void {
    if ( $query->is_front_page() && $query->is_main_query() ) {
        $query->set( 'post_type', 'some_post_type' );
    }
}

Method 2

The main query is the one triggered automatically when WordPress has determined what to show for the request URI.

Later instances of WP_Query are never the main query, but you can use them to replace the main query’s result in $GLOBALS['wp_the_query']. Don’t do that.


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

Leave a Comment