
WordPress插件开发入门基础教程
wp_count_attachments ( $mime_type = '' )
wp_count_attachments: 这是一个返回媒体库中附件数量的函数。它可以用来获得媒体库的概况,并跟踪附件的数量。
计算mime类型的附件数量。
如果你设置了可选的mime_type参数,那么仍将返回一个数组,但将只有你要找的项目。它不会给你一个文章的附件的数量。你可以通过计算该文章的子句数量来获得。
function wp_count_attachments( $mime_type = '' ) { global $wpdb; $cache_key = sprintf( 'attachments%s', ! empty( $mime_type ) ? ':' . str_replace( '/', '_', implode( '-', (array) $mime_type ) ) : '' ); $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' ); } /** * Modifies returned attachment counts by mime type. * * @since 3.7.0 * * @param stdClass $counts An object containing the attachment counts by * mime type. * @param string|string[] $mime_type Array or comma-separated list of MIME patterns. */ return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type ); }