Users: Use a separate variable for the post counts query in wp_list_authors().

This avoids a collision if `wp_list_authors()` is called with the `optioncount` parameter enabled, and the resulting array for the post counts query contains a key that matches the ID of a user who does not have any posts.

Follow-up to [54262].

Props peterwilsoncc, johnbillion, lifeboat, brookedot, thedaysse, Toru.
Fixes #57011.

git-svn-id: https://develop.svn.wordpress.org/trunk@55444 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov
2023-03-01 15:37:06 +00:00
parent 33de1d77a5
commit 0a91a53cf7
2 changed files with 28 additions and 2 deletions

View File

@@ -481,14 +481,15 @@ function wp_list_authors( $args = '' ) {
$post_counts = apply_filters( 'pre_wp_list_authors_post_counts_query', false, $parsed_args );
if ( ! is_array( $post_counts ) ) {
$post_counts = $wpdb->get_results(
$post_counts = array();
$post_counts_query = $wpdb->get_results(
"SELECT DISTINCT post_author, COUNT(ID) AS count
FROM $wpdb->posts
WHERE " . get_private_posts_cap_sql( 'post' ) . '
GROUP BY post_author'
);
foreach ( (array) $post_counts as $row ) {
foreach ( (array) $post_counts_query as $row ) {
$post_counts[ $row->post_author ] = $row->count;
}
}

View File

@@ -146,6 +146,31 @@ class Tests_User_wpListAuthors extends WP_UnitTestCase {
);
}
/**
* Ensures the 'optioncount' parameter does not throw an error when there are authors without posts.
*
* @ticket 57011
*/
public function test_wp_list_authors_optioncount_should_not_error_for_empty_authors() {
/*
* The main purpose of this test is to ensure that the error below is not thrown:
*
* Error: Object of class stdClass could not be converted to string
*
* In place of direct testing we ensure `wp_list_authors()` returns a list of authors
* at least one of which is empty.
*/
$actual = wp_list_authors(
array(
'optioncount' => true,
'hide_empty' => false,
'exclude_admin' => false,
'echo' => false,
)
);
$this->assertStringContainsString( '(0)', $actual );
}
public function test_wp_list_authors_exclude_admin() {
self::factory()->post->create(
array(