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.
Actually, it’s $wp_the_query. $wp_query isn’t always the main loop.
Fixed, thanks!
I want to try to start capturing little code snippets here that I think are useful (many from the Hackers list), but it’s still bugging me that I didn’t bother to test this properly on my initial post and Nacin had to take his time to correct me. I’ll try to avoid this mistake in the future; after all, there are so many new ones to make.
[…] it in line with the rest of the WordPress Administration.Very handy indeed!Alex King posted a little code snippet for detecting the “Main” Loop in WordPress.And that wraps it up for this week (or the last couple of weeks). If you have a link […]
Thanks Alex, I was just using $query->set for the first time to access more post types. This helped me narrow down where to do that, so it didn’t come in on widget loops, too. Very helpful 🙂
There’s a better way in 3.3.
That didn’t work for me the other day, so I went back to this version. But I ran into issues once I was looking at category pages – they weren’t finding the other post types. Using $query->is_main_query() worked! So, okay, going w/ the new+improved version!