Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

marked as duplicate by Rarst Jan 15 '13 at 20:39

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
I suggest reading this slideshare.net/andrewnacin/… –  Wyck Jan 15 '13 at 20:28

2 Answers 2

up vote 6 down vote accepted

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;
    }
}
share|improve this answer
2  
Tom, thank you so much! Yeah that was the exact problem: I just forgot to call those functions from $query. –  Delay Jan 15 '13 at 20:44

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.

share|improve this answer

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