Make WordPress Core

Changeset 54255


Ignore:
Timestamp:
09/20/2022 02:20:57 PM (2 years ago)
Author:
audrasjb
Message:

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.

Location:
trunk
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/post.php

    r54234 r54255  
    30913091    global $wpdb;
    30923092
    3093     $and   = wp_post_mime_type_where( $mime_type );
    3094     $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 );
    3095 
    3096     $counts = array();
    3097     foreach ( (array) $count as $row ) {
    3098         $counts[ $row['post_mime_type'] ] = $row['num_posts'];
    3099     }
    3100     $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
     3093    $cache_key = sprintf(
     3094        'attachments%s',
     3095        ! empty( $mime_type ) ? ':' . str_replace( '/', '_', implode( '-', (array) $mime_type ) ) : ''
     3096    );
     3097
     3098    $counts = wp_cache_get( $cache_key, 'counts' );
     3099    if ( false == $counts ) {
     3100        $and   = wp_post_mime_type_where( $mime_type );
     3101        $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 );
     3102
     3103        $counts = array();
     3104        foreach ( (array) $count as $row ) {
     3105            $counts[ $row['post_mime_type'] ] = $row['num_posts'];
     3106        }
     3107        $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
     3108
     3109        wp_cache_set( $cache_key, (object) $counts, 'counts' );
     3110    }
    31013111
    31023112    /**
Note: See TracChangeset for help on using the changeset viewer.