From e5b586bfd02f1a870d38d383922fd0aa0f87889a Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Thu, 10 Aug 2023 10:24:29 +0000 Subject: [PATCH] Users: Correct the logic for `switch_to_blog()` in `WP_User_Query::generate_cache_key()`. If `$blog_id` equals `0`, it should be treated as the current site ID, and there is no need to switch to a different site. This commit prevents an unnecessary call to `switch_to_blog()` on single site to avoid a fatal error when using `'orderby' => 'post_count'` and the deprecated `'who' => 'authors'` parameter: {{{ Uncaught Error: Call to undefined function switch_to_blog() in wp-includes/class-wp-user-query.php:1077 }}} Follow-up to [55657]. Props dd32, austinginder, RavanH, mukesh27. Fixes #59011. git-svn-id: https://develop.svn.wordpress.org/trunk@56381 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-wp-user-query.php | 7 +++++-- tests/phpunit/tests/user/queryCache.php | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-user-query.php b/src/wp-includes/class-wp-user-query.php index 04f13430f5..c5d66404ea 100644 --- a/src/wp-includes/class-wp-user-query.php +++ b/src/wp-includes/class-wp-user-query.php @@ -1071,12 +1071,15 @@ class WP_User_Query { if ( isset( $args['blog_id'] ) ) { $blog_id = absint( $args['blog_id'] ); } - if ( ( $args['has_published_posts'] && $blog_id ) || in_array( 'post_count', $ordersby, true ) ) { - $switch = get_current_blog_id() !== $blog_id; + + if ( $args['has_published_posts'] || in_array( 'post_count', $ordersby, true ) ) { + $switch = $blog_id && get_current_blog_id() !== $blog_id; if ( $switch ) { switch_to_blog( $blog_id ); } + $last_changed .= wp_cache_get_last_changed( 'posts' ); + if ( $switch ) { restore_current_blog(); } diff --git a/tests/phpunit/tests/user/queryCache.php b/tests/phpunit/tests/user/queryCache.php index 91e84c4e01..d8d26286a7 100644 --- a/tests/phpunit/tests/user/queryCache.php +++ b/tests/phpunit/tests/user/queryCache.php @@ -778,4 +778,26 @@ class Tests_User_Query_Cache extends WP_UnitTestCase { $this->assertSame( $cache_key_1, $cache_key_2, 'Cache key differs when using wpdb placeholder.' ); } + + /** + * Verifies that generate_cache_key() does not throw a fatal error for switch_to_blog() + * with 'orderby' => 'post_count' and the deprecated 'who' => 'authors' parameter. + * + * @ticket 59011 + * @covers ::generate_cache_key + * + * @expectedDeprecated WP_User_Query + */ + public function test_generate_cache_key_with_orderby_post_count_and_deprecated_who_parameter() { + $query = new WP_User_Query( + array( + 'fields' => 'ID', + 'orderby' => 'post_count', + 'order' => 'DESC', + 'who' => 'authors', + ) + ); + + $this->assertNotEmpty( $query->get_results() ); + } }