X

Check If Post Has More Than One Image Attachment

Snippets by IsItWP

Do you want to check whether post has one or more image attachments? We have created a quick code snippet that you can use to check if post has more than one image attachment in WordPress.

Instructions:

All you have to do is add this code to your theme’s single.php file, then add code on lines 9 and 11 for whatever you would like the code to do depending on whether the post has one or more image attachments.

<?php
$attachments = get_children(
    array(
	'post_type' => 'attachment',
	'post_mime_type' => 'image',
	'post_parent' => $post->ID
    ));
if(count($attachments) > 1) { ?>
    <!-- Do something like show a slider -->
<?php } else { ?>
    <!-- Display a single image -->
<?php } ?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 28 best WordPress resume themes to create best impression and 10 best WordPress testimonial plugins to add social proof.

Comments   Leave a Reply

  1. You can renew this snippet. Will be very useful to theme developers for Blog icons if post has gallery.
    Now when WordPress has select dropdown custom image sizes even for galleries. People can chose only one image in gallery and put it at the top of the Post. Needed for Jetpack carousel for instance.
    This snippet will make it easy to dismiss all Posts with “one image” gallery (not really gallery).

  2. Awesome! Thanks a lot. This really worked for me.

  3. Kevin,

    Your are the man. I’ve spent the whole night and tearing my hair out just trying to do this. I finally searched for this phrase “php to display wordpress gallery if there are 2 images or more” and got your website. You are the greatest!

  4. oh my god! thank you man! this is awesome.

  5. you saved my life with this snippet!!! thanks!!!!

    1. No problem anytime 🙂

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!