WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Count number of Images in a native WordPress gallery/post (6 posts)

  1. Matt Rude
    Member
    Posted 4 years ago #

    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

  2. ryans149
    Member
    Posted 4 years ago #

  3. ddegner
    Member
    Posted 4 years ago #

    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.

  4. Mark / t31os
    Moderator
    Posted 4 years ago #

    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)
    ?>
  5. ddegner
    Member
    Posted 4 years ago #

    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;
    ?>
  6. Mark / t31os
    Moderator
    Posted 4 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags