Support » Fixing WordPress » Count number of Images in a native WordPress gallery/post

  • Resolved Matt Rude

    (@mattrude)


    I’m looking to count the number of images that are in a post’s native WordPress gallery. I have found many examples to count the number of comments, or posts, but not children objects.

    Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • I’m still looking for this on my site, but I need it on the archives and index pages. I’d expect it to be pretty easy.

    It is pretty easy, what exactly do you want to do, count the total number of files in the media library?

    <?php
    $total_attachments = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment'");
    
    echo $total_attachments; // Will be 0 if there were no matches .. or the positive numeric value if found (eg 1, 5, 100 or whatever)
    ?>

    That’s close but we want to count the attachments only for the current post.

    One way might be close to this, but it appears to spit out random numbers.

    <?php
    $id=the_ID();
    $total_attachments = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' && ID=$id");
    echo $total_attachments;
    ?>

    Works for me using a test ID value.

    $id = 1;
    $total_attachments = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' AND ID = $id");
    echo $total_attachments;

    NOTE: Has nothing to do with the fact i replaced the && with AND, i just prefer capped words for readability.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Count number of Images in a native WordPress gallery/post’ is closed to new replies.