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/tests/phpunit/tests/query/conditionals.php

    r53400 r53429  
    16611661    }
    16621662
     1663    /**
     1664     * @ticket 55722
     1665     *
     1666     * @dataProvider data_loop_functions_do_not_trigger_a_fatal_error_if_wp_query_is_not_set
     1667     *
     1668     * @param string     $function_name The name of the function to test.
     1669     * @param false|null $expected      Expected return value.
     1670     */
     1671    public function test_loop_functions_do_not_trigger_a_fatal_error_if_wp_query_is_not_set( $function_name, $expected ) {
     1672        unset( $GLOBALS['wp_query'] );
     1673
     1674        $this->assertSame( $expected, call_user_func( $function_name ) );
     1675    }
     1676
     1677    /**
     1678     * Data provider.
     1679     *
     1680     * @return array[] Test parameters {
     1681     *     @type string     $function_name The name of the function to test.
     1682     *     @type false|null $expected      Expected return value.
     1683     * }
     1684     */
     1685    public function data_loop_functions_do_not_trigger_a_fatal_error_if_wp_query_is_not_set() {
     1686        return array(
     1687            array( 'have_posts', false ),
     1688            array( 'in_the_loop', false ),
     1689            array( 'rewind_posts', null ),
     1690            array( 'the_post', null ),
     1691            array( 'have_comments', false ),
     1692            array( 'the_comment', null ),
     1693        );
     1694    }
     1695
    16631696}
Note: See TracChangeset for help on using the changeset viewer.