Make WordPress Core

Ticket #55227: 55227.diff

File 55227.diff, 2.1 KB (added by jeherve, 2 years ago)

Add caching to wp_count_attachments

  • src/wp-includes/post.php

     
    30833083}
    30843084
    30853085/**
     3086 * Return the cache key for wp_count_attachments() based on the passed mime type.
     3087 *
     3088 * @since 6.0.0
     3089 * @access private
     3090 *
     3091 * @param string|string[] $mime_type Optional. Array or comma-separated list of
     3092 *                                   MIME patterns. Default empty.
     3093 * @return string The cache key.
     3094 */
     3095function _count_attachments_cache_key( $mime_type = '' ) {
     3096        $cache_key = sprintf(
     3097                'attachments%s',
     3098                ! empty( $mime_type ) ? ':' . str_replace( '/', '_', implode( '-', (array) $mime_type ) ) : ''
     3099        );
     3100
     3101        return $cache_key;
     3102}
     3103
     3104/**
    30863105 * Count number of attachments for the mime type(s).
    30873106 *
    30883107 * If you set the optional mime_type parameter, then an array will still be
     
    31013120function wp_count_attachments( $mime_type = '' ) {
    31023121        global $wpdb;
    31033122
     3123        $cache_key = _count_attachments_cache_key( $mime_type );
     3124
     3125        $counts = wp_cache_get( $cache_key, 'counts' );
     3126        if ( false !== $counts ) {
     3127                /** This filter is documented in wp-includes/post.php */
     3128                return apply_filters( 'wp_count_attachments', $counts, $mime_type );
     3129        }
     3130
    31043131        $and   = wp_post_mime_type_where( $mime_type );
    31053132        $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 );
    31063133
     
    31103137        }
    31113138        $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
    31123139
     3140        $counts = (object) $counts;
     3141        wp_cache_set( $cache_key, $counts, 'counts' );
     3142
    31133143        /**
    31143144         * Modify returned attachment counts by mime type.
    31153145         *
     
    31193149         *                                   mime type.
    31203150         * @param string|string[] $mime_type Array or comma-separated list of MIME patterns.
    31213151         */
    3122         return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
     3152        return apply_filters( 'wp_count_attachments', $counts, $mime_type );
    31233153}
    31243154
    31253155/**