Skip to content

Commit

Permalink
Canonical: Protect against error for term not exists queries.
Browse files Browse the repository at this point in the history
Prevent term `NOT EXISTS` queries causing `redirect_canonical()` to throw a fatal error in PHP 8 and above, or a warning in earlier versions.

This ensures the `tax_query`'s `terms` property both exists and is countable before attempting to count it.

Props codesdnc, SergeyBiryukov, kadamwhite, costdev, miguelaxcar.
Fixes #55955.



git-svn-id: https://develop.svn.wordpress.org/trunk@54785 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information
peterwilsoncc committed Nov 10, 2022
1 parent 19d5bd0 commit b930414
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/wp-includes/canonical.php
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,9 @@ function redirect_canonical( $requested_url = null, $do_redirect = true ) {
$term_count = 0;

foreach ( $wp_query->tax_query->queried_terms as $tax_query ) {
$term_count += count( $tax_query['terms'] );
if ( isset( $tax_query['terms'] ) && is_countable( $tax_query['terms'] ) ) {
$term_count += count( $tax_query['terms'] );
}
}

$obj = $wp_query->get_queried_object();
Expand Down
27 changes: 27 additions & 0 deletions tests/phpunit/tests/canonical.php
Original file line number Diff line number Diff line change
Expand Up @@ -375,4 +375,31 @@ public function test_utf8_query_keys_canonical() {

delete_option( 'page_on_front' );
}

/**
* Ensure NOT EXISTS queries do not trigger not-countable or undefined array key errors.
*
* @ticket 55955
*/
public function test_feed_canonical_with_not_exists_query() {
// Set a NOT EXISTS tax_query on the global query.
$global_query = $GLOBALS['wp_query'];
$GLOBALS['wp_query'] = new WP_Query(
array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'operator' => 'NOT EXISTS',
),
),
)
);

$url = redirect_canonical( get_term_feed_link( self::$terms['/category/parent/'] ), false );
// Restore original global.
$GLOBALS['wp_query'] = $global_query;

$this->assertNull( $url );
}
}

0 comments on commit b930414

Please sign in to comment.