is_main_query()
Checks if the action is being executed in the main WordPress loop. Conditional tag.
The function should only be used within loops, as the tag is intended to determine the main WordPress loop.
1 time — 0.000011 sec (very fast) | 50000 times — 0.01 sec (speed of light) | PHP 7.0.14, WP 4.7
No Hooks.
Returns
true|false.
Usage
if( is_main_query() ){ ... };
Examples
#1 How to exclude a category from the main loop
An alternative example showing how to change only the main loop and exclude category 5 from it.
Of course we will exclude category 5 only if the cat parameter is not specified in the query (no category is specified directly). To do that let's use pre_get_posts filter:
/**
* If the global query is for a category, exclude category 5.
*
* @param WP_Query $query Global WP_Query instance.
*/
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' );
}
}
Here we use WP_Query->is_main_query() instead of is_main_query(), because in some cases it may be invalid.
#2 Execute the code only if it is the main loop:
if( is_main_query() ){
// here is the code to be executed.
}
Notes
- Global. WP_Query.
$wp_queryWordPress Query object.
Changelog
| Since 3.3.0 | Introduced. |