is_main_query(). * 3. Alternate query posts are checked in the_posts or pre_get_posts & ! $wp_query->is_main_query(). * 4. Blocks are checked in the content_control/should_hide_block filter. * * @param \WP_Query|null $query Query object. * * @return string 'main', 'main/posts', 'posts', 'main/blocks', 'blocks`. */ function current_query_context( $query = null ) { global $cc_current_query_context; if ( isset( $cc_current_query_context ) ) { return $cc_current_query_context; } $query = get_query( $query ); $is_main = $query->is_main_query(); // Blocks in the main page or other locations. if ( doing_filter( 'content_control/should_hide_block' ) ) { return $is_main ? 'main/blocks' : 'blocks'; } // Main query (page/psst/home/search/archive etc) (template_redirect). if ( $is_main && doing_action( 'template_redirect' ) ) { return 'main'; } if ( doing_filter( 'pre_get_posts' ) || doing_filter( 'the_posts' ) ) { return $is_main ? 'main/posts' : 'posts'; } // Default to posts. return 'posts'; } /** * Set the current rule (globaly accessible). * * Because we check posts in `the_posts`, we can't trust the global $wp_query * has been set yet, so we need to manage global state ourselves. * * @param string $query WP_Query object. * * @return void */ function set_rules_query( $query ) { global $cc_current_query; $cc_current_query = $query; } /** * Check and overload global post if needed. * * This has no effect when checking global queries ($post_id = null). * * @param int|null $post_id Post ID. * * @return bool */ function setup_post( $post_id = null ) { global $post; if ( is_null( $post_id ) ) { return false; } $current_post_id = isset( $post ) ? $post->ID : null; $overload_post = isset( $post_id ) && ( ( is_object( $post_id ) && $post_id->ID !== $current_post_id ) || ( is_int( $post_id ) && $post_id !== $current_post_id ) ); if ( $overload_post ) { // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $post = get_post( $post_id ); setup_postdata( $post ); } return $overload_post; } /** * Check and clear global post if needed. * * @param bool $overload_post Whether post was overloaded. * * @return void */ function clear_post( $overload_post = false ) { if ( $overload_post ) { // Reset global post object. wp_reset_postdata(); } }