is_main_query()判断是否在主查询中

目录

描述

The is_main_query() function is a conditional function that can be used to evaluate whether the current query (such as within the loop) is the "main" query (as opposed to a secondary query).

This function is most commonly used within hooks to distinguish WordPress' main query (for a page, post, or archive) from a custom/secondary query.

is_main_query() may be used with both front-end queries (theme templates, plugins, etc.), as well as admin queries. It will return true if the current query is the main query, and false if not.

is_main_query() 描述

用法

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?phpif ( is_main_query() ) {    // do stuff}

is_main_query() 用法

返回值

(boolean) 

True on success, false on failure.

is_main_query() 返回值

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

add_action( 'pre_get_posts', 'foo_modify_query_exclude_category' );
function foo_modify_query_exclude_category( $query ) {
    if ( ! is_admin() && $query->is_main_query() && ! $query->get( 'cat' ) )
        $query->set( 'cat', '-5' );
}

is_main_query() 示例

历史

添加于 版本: 3.3

is_main_query() 历史

源文件

is_main_query() 函数的代码位于 wp-includes/query.php, starting line 719.

WP_Query::is_main_query() 函数的代码位于 wp-includes/query.php, starting line 3816.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Is the query the main query?
 *
 * @since 3.3.0
 *
 * @global WP_Query $wp_query
 *
 * @return bool
 */
function is_main_query() {
	if ( 'pre_get_posts' === current_filter() ) {
		$message = sprintf( __( 'In %1$s, use the %2$s method, not the %3$s function. See %4$s.' ),
			'pre_get_posts', 'WP_Query::is_main_query()', 'is_main_query()', __( 'https://codex.wordpress.org/Function_Reference/is_main_query' ) );
		_doing_it_wrong( __FUNCTION__, $message, '3.7' );
	}

	global $wp_query;
	return $wp_query->is_main_query();
}

is_main_query() 源文件