Identify which loop you are hooking into; primary or secondary?

What is the most efficient way to determine which loop I’m in?

I have a few plugins that alter the query by hooking into various parts of WP_Query::get_posts(), through the usual suspects, ie posts_where, posts_join, etc. I don’t want to effect every loop on every page though, so right now I’m running a debug_backtrace() and checking for the existence of the main() or query_posts() function as necessary.

There has to be a more efficient way to identify the primary loop and sub-loops on each page. Something I keep missing when I pore over the query vars and other aspects of the request, something that’s unique to each one. How would you go about doing this?

2 Answers
2

Just a quick update that a new method is_main_query() has been introduced in WP 3.3.

Example:

add_action( 'pre_get_posts', 'foo_modify_query_exclude_category' );
function foo_modify_query_exclude_category( $query ) {
    if ( $query->is_main_query() && ! $query->get( 'cat' ) )
    $query->set( 'cat', '-5' );
}

Resources:

  • WPDevel: New API in 3.3: is_main_query()
  • Codex reference: is_main_query()
  • Related Trac Ticket #18677

Leave a Comment