4

I mention "full website" because I don't need the number of attachments on one post (as answered in many questions). I basically need a function that returns the number of uploaded images (attached and unattached) on the website, excluding non-image files.

I've done some research, but there isn’t any direct function that counts only the images. What is the most simple way to do this?

6

There's a handy built-in function, namely wp_count_attachments().

We can filter out images with wp_count_attachments( $mime_type = 'image' ) that returns an object like:

stdClass Object
(
    [image/gif] => 9
    [image/jpeg] => 121
    [image/png] => 20
    [image/x-icon] => 6
    [trash] => 0
)

So we can use the one-liner:

$count = array_sum( (array) wp_count_attachments( $mime_type = 'image' ) );

for the total number of images.

1

The simplest way I know is:

global $wpdb ;

$sql = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment'" ;

$count = (int) $wpdb->get_var ($sql) ;

You could also use WP_Query, altho doing so is more expensive:

$args = array (
    'post_type' => 'attachment',
    'post_status' => 'inherit',
    'posts_per_page' => 0,
    ) ;
$attatchments = new WP_Query ($args) ;

$count = $attatchments->found_posts ;

note: setting 'posts_per_page' => 0 and reading found_posts is an optimization when using WP_Query in cases like this that I just learned from the answer to another question here on WPSE a few days ago...I don't remember which question it was, otherwise I'd credit the author for the tip.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.