9

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.

1

2 Answers 2

10

The filter has a bug in it, namely when it calls is_main_query, it's not checking if the passed $query is the main query, it's 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' );
    }
}
1
  • 2
    Tom, thank you so much! Yeah that was the exact problem: I just forgot to call those functions from $query.
    – Jake
    Commented Jan 15, 2013 at 20:44
4

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.