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.

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?

share|improve this question
    
Any progress on this question? If you've found an answer elsewhere, come back here and post your solution as an answer for others to benefit. –  Tom Auger Sep 30 '11 at 20:49
    
see wordpress.stackexchange.com/questions/28670/…. Also I noticed that using in_the_loop() works too... –  onetrickpony Nov 21 '11 at 2:55

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:

share|improve this answer

If secondary loops are called properly (i.e. by not mucking with query_posts(), and by setting a variable $myloop equal to get_posts() or new WP_Query), then identifying said loop is as simple as referencing the variable.

If you need to call a second loop from within the primary Loop, and you call setup_postdata() in the secondary loop, you may need to call wp_reset_query() when you close your secondary loop, so that your template tags revert to applying to the primary Loop.

share|improve this answer
    
Thanks Chip, but I probably should have mentioned that the plugin is most likely unaware of its environment to that degree. I won't be responsible for every theme that the plugin is running in and unable to ensure that each one is using the loop appropriately. –  mwaterous Jun 22 '11 at 9:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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