wp_count_attachments

Count number of attachments for the mime type(s).

Description

(object) wp_count_attachments( (string) $mime_type = '' ); 

If you set the optional mime_type parameter, then an array will still be returned, but will only have the item you are looking for. It does not give you the number of attachments that are children of a post. You can get that by counting the number of children that post has.

Returns (object)

An object containing the attachment counts by mime type.

Parameters (1)

0. $mime_type — Optional. (string) => ''
Array or comma-separated list of MIME patterns. Default empty.

Usage

  1. if ( !function_exists( 'wp_count_attachments' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Optional. Array or comma-separated list of 
  5. // MIME patterns. Default empty. 
  6. $mime_type = ''; 
  7.  
  8. // NOTICE! Understand what this does before running. 
  9. $result = wp_count_attachments($mime_type); 
  10.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function wp_count_attachments( $mime_type = '' ) { 
  2. global $wpdb; 
  3.  
  4. $and = wp_post_mime_type_where( $mime_type ); 
  5. $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 ); 
  6.  
  7. $counts = array(); 
  8. foreach ( (array) $count as $row ) { 
  9. $counts[ $row['post_mime_type'] ] = $row['num_posts']; 
  10. $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and"); 
  11.  
  12. /** 
  13. * Modify returned attachment counts by mime type. 
  14. * @since 3.7.0 
  15. * @param object $counts An object containing the attachment counts by 
  16. * mime type. 
  17. * @param string $mime_type The mime type pattern used to filter the attachments 
  18. * counted. 
  19. */ 
  20. return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );