Make WordPress Core

Changeset 53395


Ignore:
Timestamp:
05/14/2022 03:08:58 PM (2 years ago)
Author:
SergeyBiryukov
Message:

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.

Location:
trunk
Files:
2 edited

Legend:

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

    r51154 r53395  
    901901function is_main_query() {
    902902    global $wp_query;
     903
     904    if ( ! isset( $wp_query ) ) {
     905        _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '6.1.0' );
     906        return false;
     907    }
    903908
    904909    if ( 'pre_get_posts' === current_filter() ) {
  • trunk/tests/phpunit/tests/query/conditionals.php

    r52010 r53395  
    16171617    }
    16181618
     1619    /**
     1620     * @ticket 55104
     1621     * @expectedIncorrectUsage is_main_query
     1622     */
     1623    public function test_is_main_query_returns_false_if_wp_query_is_not_set() {
     1624        unset( $GLOBALS['wp_query'] );
     1625
     1626        $this->assertFalse( is_main_query() );
     1627    }
     1628
    16191629}
Note: See TracChangeset for help on using the changeset viewer.