WordPress Code Snippet to Detect “Main” Loop

Cribbed from the WP-Hackers list, the following sample code should give you a good way to test if the current “in the loop” action is within the main loop or a different loop:

function main_loop_test($query) {
  global $wp_the_query;
  if ($query === $wp_the_query) {
    echo "main loop";
  }
}
add_action('loop_start', 'main_loop_test');

Thanks Nacin and Konrad.

This is useful if you’re creating a plugin that needs to be compatible with multiple themes, otherwise for a theme implementation there are better ways to check for this (for example, setting/unsetting a bit around the main loop call).

UPDATE: As of WordPress 3.3, use is_main_query() instead.