Skip to content

Instantly share code, notes, and snippets.

@justintadlock
Last active February 11, 2024 20:23
Show Gist options
  • Save justintadlock/4551657 to your computer and use it in GitHub Desktop.
Save justintadlock/4551657 to your computer and use it in GitHub Desktop.
A conditional tag for checking if we're in the core WP main query + loop.
<?php
/**
* Conditional to test if we're in the loop of the main query on a WordPress page.
* Please note that checking `in_the_loop() && is_main_query()` will NOT work in
* this scenario.
*/
add_action( 'loop_start', 'my_loop_start' );
add_action( 'loop_end', 'my_loop_end' );
function my_loop_start( $query ) {
$GLOBALS['my_in_main_loop'] = $query->is_main_query();
}
function my_loop_end( $query ) {
$GLOBALS['my_in_main_loop'] = false;
}
function my_in_main_loop() {
return (bool) $GLOBALS['my_in_main_loop'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment