diff --git a/src/wp-includes/query.php b/src/wp-includes/query.php index c38a11c083..27d8c26fa4 100644 --- a/src/wp-includes/query.php +++ b/src/wp-includes/query.php @@ -3900,15 +3900,17 @@ class WP_Query { // For other tax queries, grab the first term from the first clause. $tax_query_in_and = wp_list_filter( $this->tax_query->queried_terms, array( 'operator' => 'NOT IN' ), 'NOT' ); - $queried_taxonomies = array_keys( $tax_query_in_and ); - $matched_taxonomy = reset( $queried_taxonomies ); - $query = $tax_query_in_and[ $matched_taxonomy ]; + if ( ! empty( $tax_query_in_and ) ) { + $queried_taxonomies = array_keys( $tax_query_in_and ); + $matched_taxonomy = reset( $queried_taxonomies ); + $query = $tax_query_in_and[ $matched_taxonomy ]; - if ( $query['terms'] ) { - if ( 'term_id' == $query['field'] ) { - $term = get_term( reset( $query['terms'] ), $matched_taxonomy ); - } else { - $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy ); + if ( $query['terms'] ) { + if ( 'term_id' == $query['field'] ) { + $term = get_term( reset( $query['terms'] ), $matched_taxonomy ); + } else { + $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy ); + } } } } diff --git a/tests/phpunit/tests/query.php b/tests/phpunit/tests/query.php index 3217ac5c37..c1aa6df309 100644 --- a/tests/phpunit/tests/query.php +++ b/tests/phpunit/tests/query.php @@ -91,4 +91,35 @@ class Tests_Query extends WP_UnitTestCase { $this->assertCount( 1, $query->get( 'tag_slug__in' ) ); $this->assertEquals( $query->get_queried_object(), $tag ); } -} \ No newline at end of file + + /** + * @ticket 31246 + */ + public function test_get_queried_object_should_return_null_when_is_tax_is_true_but_the_taxonomy_args_have_been_removed_in_a_parse_query_callback() { + // Don't override the args provided below. + remove_action( 'pre_get_posts', array( $this, 'pre_get_posts_tax_category_tax_query' ) ); + register_taxonomy( 'wptests_tax', 'post' ); + $terms = $this->factory->term->create_many( 2, array( + 'taxonomy' => 'wptests_tax', + ) ); + + $posts = $this->factory->post->create_many( 2 ); + + wp_set_object_terms( $posts[0], array( $terms[0] ), 'wptests_tax' ); + wp_set_object_terms( $posts[1], array( $terms[1] ), 'wptests_tax' ); + + add_action( 'parse_query', array( $this, 'filter_parse_query_to_remove_tax' ) ); + $q = new WP_Query( array( + 'fields' => 'ids', + 'wptests_tax' => $terms[1], + ) ); + + remove_action( 'parse_query', array( $this, 'filter_parse_query_to_remove_tax' ) ); + + $this->assertNull( $q->get_queried_object() ); + } + + public function filter_parse_query_to_remove_tax( $q ) { + unset( $q->query_vars['wptests_tax'] ); + } +}