Make WordPress Core


Ignore:
Timestamp:
05/22/2022 03:15:47 PM (2 years ago)
Author:
SergeyBiryukov
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/query.php

    r53395 r53429  
    940940function have_posts() {
    941941    global $wp_query;
     942
     943    if ( ! isset( $wp_query ) ) {
     944        return false;
     945    }
     946
    942947    return $wp_query->have_posts();
    943948}
     
    958963function in_the_loop() {
    959964    global $wp_query;
     965
     966    if ( ! isset( $wp_query ) ) {
     967        return false;
     968    }
     969
    960970    return $wp_query->in_the_loop;
    961971}
     
    970980function rewind_posts() {
    971981    global $wp_query;
     982
     983    if ( ! isset( $wp_query ) ) {
     984        return;
     985    }
     986
    972987    $wp_query->rewind_posts();
    973988}
     
    982997function the_post() {
    983998    global $wp_query;
     999
     1000    if ( ! isset( $wp_query ) ) {
     1001        return;
     1002    }
     1003
    9841004    $wp_query->the_post();
    9851005}
     
    10001020function have_comments() {
    10011021    global $wp_query;
     1022
     1023    if ( ! isset( $wp_query ) ) {
     1024        return false;
     1025    }
     1026
    10021027    return $wp_query->have_comments();
    10031028}
     
    10091034 *
    10101035 * @global WP_Query $wp_query WordPress Query object.
    1011  *
    1012  * @return null
    10131036 */
    10141037function the_comment() {
    10151038    global $wp_query;
    1016     return $wp_query->the_comment();
     1039
     1040    if ( ! isset( $wp_query ) ) {
     1041        return;
     1042    }
     1043
     1044    $wp_query->the_comment();
    10171045}
    10181046
Note: See TracChangeset for help on using the changeset viewer.