is_main_query()WP 3.3.0

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

0

#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

#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_query WordPress Query object.

Changelog

Since 3.3.0 Introduced.

is_main_query() code WP 6.9.1

function is_main_query() {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '6.1.0' );
		return false;
	}

	if ( 'pre_get_posts' === current_filter() ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: 1: pre_get_posts, 2: WP_Query->is_main_query(), 3: is_main_query(), 4: Documentation URL. */
				__( 'In %1$s, use the %2$s method, not the %3$s function. See %4$s.' ),
				'<code>pre_get_posts</code>',
				'<code>WP_Query->is_main_query()</code>',
				'<code>is_main_query()</code>',
				__( 'https://developer.wordpress.org/reference/functions/is_main_query/' )
			),
			'3.7.0'
		);
	}

	return $wp_query->is_main_query();
}