Skip to content

Commit 959aa03

Browse files
committed
Posts, Post Types: Refactor preparation of query for wp_count_posts().
Follow-up to [60788]. Props mukesh27, westonruter. See #61097. git-svn-id: https://develop.svn.wordpress.org/trunk@60792 602fd350-edb4-49c9-b593-d223f7449a82
1 parent 89f26de commit 959aa03

File tree

2 files changed

+14
-16
lines changed

2 files changed

+14
-16
lines changed

src/wp-includes/post.php

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3406,8 +3406,7 @@ function wp_count_posts( $type = 'post', $perm = '' ) {
34063406
! current_user_can( get_post_type_object( $type )->cap->read_private_posts )
34073407
) {
34083408
// Optimized query uses subqueries which can leverage DB indexes for better performance. See #61097.
3409-
$query = $wpdb->prepare(
3410-
"
3409+
$query = "
34113410
SELECT post_status, COUNT(*) AS num_posts
34123411
FROM (
34133412
SELECT post_status
@@ -3418,24 +3417,23 @@ function wp_count_posts( $type = 'post', $perm = '' ) {
34183417
FROM {$wpdb->posts}
34193418
WHERE post_type = %s AND post_status = 'private' AND post_author = %d
34203419
) AS filtered_posts
3421-
",
3422-
$type,
3423-
$type,
3424-
get_current_user_id()
3425-
);
3420+
";
3421+
$args = array( $type, $type, get_current_user_id() );
34263422
} else {
3427-
$query = $wpdb->prepare(
3428-
"
3423+
$query = "
34293424
SELECT post_status, COUNT(*) AS num_posts
34303425
FROM {$wpdb->posts}
34313426
WHERE post_type = %s
3432-
",
3433-
$type
3434-
);
3427+
";
3428+
$args = array( $type );
34353429
}
34363430

3437-
$query .= ' GROUP BY post_status';
3438-
$results = (array) $wpdb->get_results( $query, ARRAY_A );
3431+
$query .= ' GROUP BY post_status';
3432+
3433+
$results = (array) $wpdb->get_results(
3434+
$wpdb->prepare( $query, ...$args ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Placeholders are used in the string contained in the variable.
3435+
ARRAY_A
3436+
);
34393437
$counts = array_fill_keys( get_post_stati(), 0 );
34403438

34413439
foreach ( $results as $row ) {

tests/phpunit/tests/post.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ public function test_wp_count_posts() {
196196
* read private posts.
197197
*
198198
* @ticket 61097
199+
*
199200
* @covers ::wp_count_posts
200201
*/
201202
public function test_wp_count_posts_readable_excludes_unreadable_private_posts() {
@@ -222,8 +223,7 @@ public function test_wp_count_posts_readable_excludes_unreadable_private_posts()
222223
)
223224
);
224225

225-
$current_user_id = self::$user_ids['author'];
226-
wp_set_current_user( $current_user_id );
226+
wp_set_current_user( self::$user_ids['author'] );
227227

228228
$count = wp_count_posts( $post_type, 'readable' );
229229
$this->assertEquals( 5, $count->publish );

0 commit comments

Comments
 (0)