wp_count_attachments() WordPress Function

The wp_count_attachments() function is a built-in function in WordPress that allows you to count the number of attachments for a given post.

wp_count_attachments( string|string[] $mime_type = '' ) #

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


Description

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.


Top ↑

Parameters

$mime_type

(string|string[])(Optional) Array or comma-separated list of MIME patterns.

Default value: ''


Top ↑

Return

(stdClass) An object containing the attachment counts by mime type.


Top ↑

Source

File: wp-includes/post.php

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 );

	$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" );

	/**
	 * Modify 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 );
}


Top ↑

Changelog

Changelog
VersionDescription
2.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More