From 3da312a9547da162e2e78474744c02a624370c81 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Sat, 14 May 2022 15:08:58 +0000 Subject: [PATCH] Query: Check if `$wp_query` is set in `is_main_query()`. This avoids a PHP fatal error and triggers a `_doing_it_wrong()` notice if `is_main_query()` is called too early, bringing consistency with all the other `is_*()` conditionals: `is_single()`, `is_home()`, etc. Follow-up to [16947], [17068], [17083], [18699], [37985]. Props vdankbaar, nhadsall, johnbillion, costdev, thijsoo, teunvgisteren, timkersten655, SergeyBiryukov. Fixes #55104. git-svn-id: https://develop.svn.wordpress.org/trunk@53395 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/query.php | 5 +++++ tests/phpunit/tests/query/conditionals.php | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/wp-includes/query.php b/src/wp-includes/query.php index b915119c35..7a210b09f1 100644 --- a/src/wp-includes/query.php +++ b/src/wp-includes/query.php @@ -901,6 +901,11 @@ function is_embed() { 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__, diff --git a/tests/phpunit/tests/query/conditionals.php b/tests/phpunit/tests/query/conditionals.php index 4ef661b21a..c4f31830d6 100644 --- a/tests/phpunit/tests/query/conditionals.php +++ b/tests/phpunit/tests/query/conditionals.php @@ -1616,4 +1616,14 @@ class Tests_Query_Conditionals extends WP_UnitTestCase { $this->assertQueryTrue( 'is_page', 'is_singular', 'is_privacy_policy' ); } + /** + * @ticket 55104 + * @expectedIncorrectUsage is_main_query + */ + public function test_is_main_query_returns_false_if_wp_query_is_not_set() { + unset( $GLOBALS['wp_query'] ); + + $this->assertFalse( is_main_query() ); + } + }