is_main_query()
Is the query the main query?
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
1 time — 0.000011 sec (very fast) | 50000 times — 0.01 sec (speed of light) | PHP 7.0.14, WP 4.7
No Hooks.
Return
true|false
. Whether the query is the main query.
Usage
is_main_query();
Examples
#1 Execute the code only if it is the main loop:
if( is_main_query() ){ // here is the code to be executed. }
#2 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.
Notes
- Global. WP_Query. $wp_query WordPress Query object.
Changelog
Since 3.3.0 | Introduced. |