From f6412575c890bf651cdaa8a2d60365c19f0d4173 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Sun, 22 May 2022 15:17:14 +0000 Subject: [PATCH] Query: Check if `$wp_query` is set in query loop functions. This avoids a PHP fatal error if any of these functions are called too early: * `have_posts()` * `in_the_loop()` * `rewind_posts()` * `the_post()` * `have_comments()` * `the_comment()` bringing some consistency with conditional tags: `is_single()`, `is_home()`, etc. This commit also removes unnecessary `return` from `the_comment()`, for consistency with `the_post()`. As `WP_Query::the_comment()` does not have a return value, this statement did not have any effect in practice. Follow-up to [4934], [8807], [16947], [17068], [17083], [49147], [53395], [53396], [53400]. Props vdankbaar, thijso, teunvgisteren, timkersten655, SergeyBiryukov. Fixes #55722. Built from https://develop.svn.wordpress.org/trunk@53429 git-svn-id: http://core.svn.wordpress.org/trunk@53018 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/query.php | 34 +++++++++++++++++++++++++++++++--- wp-includes/version.php | 2 +- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/wp-includes/query.php b/wp-includes/query.php index 7a210b09f1..d4ac780212 100644 --- a/wp-includes/query.php +++ b/wp-includes/query.php @@ -939,6 +939,11 @@ function is_main_query() { */ function have_posts() { global $wp_query; + + if ( ! isset( $wp_query ) ) { + return false; + } + return $wp_query->have_posts(); } @@ -957,6 +962,11 @@ function have_posts() { */ function in_the_loop() { global $wp_query; + + if ( ! isset( $wp_query ) ) { + return false; + } + return $wp_query->in_the_loop; } @@ -969,6 +979,11 @@ function in_the_loop() { */ function rewind_posts() { global $wp_query; + + if ( ! isset( $wp_query ) ) { + return; + } + $wp_query->rewind_posts(); } @@ -981,6 +996,11 @@ function rewind_posts() { */ function the_post() { global $wp_query; + + if ( ! isset( $wp_query ) ) { + return; + } + $wp_query->the_post(); } @@ -999,6 +1019,11 @@ function the_post() { */ function have_comments() { global $wp_query; + + if ( ! isset( $wp_query ) ) { + return false; + } + return $wp_query->have_comments(); } @@ -1008,12 +1033,15 @@ function have_comments() { * @since 2.2.0 * * @global WP_Query $wp_query WordPress Query object. - * - * @return null */ function the_comment() { global $wp_query; - return $wp_query->the_comment(); + + if ( ! isset( $wp_query ) ) { + return; + } + + $wp_query->the_comment(); } /** diff --git a/wp-includes/version.php b/wp-includes/version.php index db5e8fd4b5..ab729ba84b 100644 --- a/wp-includes/version.php +++ b/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '6.1-alpha-53428'; +$wp_version = '6.1-alpha-53429'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.