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.

2 s
2

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', 'some_name');
function some_name($query) {
    if ($query->is_front_page() && $query->is_main_query()) {
        $query->set( 'post_type', 'some_post_type' );
        return;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *