Media: Add caching to wp_count_attachments().

This changeset adds caching to `wp_count_attachments()`, for better consistency with `wp_count_posts()`.

Props jeherve, antpb, mukesh27, robinwpdeveloper, costdev.
Fixes #55227.


git-svn-id: https://develop.svn.wordpress.org/trunk@54255 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Jb Audras 2022-09-20 14:20:57 +00:00
parent beeb5a4a97
commit 0cfcb3e272
2 changed files with 49 additions and 6 deletions

View File

@ -3090,14 +3090,24 @@ function wp_count_posts( $type = 'post', $perm = '' ) {
function wp_count_attachments( $mime_type = '' ) {
global $wpdb;
$and = wp_post_mime_type_where( $mime_type );
$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
$cache_key = sprintf(
'attachments%s',
! empty( $mime_type ) ? ':' . str_replace( '/', '_', implode( '-', (array) $mime_type ) ) : ''
);
$counts = array();
foreach ( (array) $count as $row ) {
$counts[ $row['post_mime_type'] ] = $row['num_posts'];
$counts = wp_cache_get( $cache_key, 'counts' );
if ( false == $counts ) {
$and = wp_post_mime_type_where( $mime_type );
$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
$counts = array();
foreach ( (array) $count as $row ) {
$counts[ $row['post_mime_type'] ] = $row['num_posts'];
}
$counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
wp_cache_set( $cache_key, (object) $counts, 'counts' );
}
$counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
/**
* Modifies returned attachment counts by mime type.

View File

@ -0,0 +1,33 @@
<?php
/**
* @group post
* @group media
* @group upload
*
* @covers ::wp_count_attachments
*/
class Tests_Post_wpCountAttachments extends WP_UnitTestCase {
/**
* Tests that the result is cached.
*
* @ticket 55227
*/
public function test_wp_count_attachments_should_cache_the_result() {
$mime_type = 'image/jpeg';
$cache_key = 'attachments:image_jpeg';
self::factory()->post->create_many(
3,
array(
'post_type' => 'attachment',
'post_mime_type' => $mime_type,
)
);
$expected = wp_count_attachments( $mime_type );
$actual = wp_cache_get( $cache_key, 'counts' );
$this->assertEquals( $expected, $actual );
}
}