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.
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).
Awesome! Thanks a lot. This really worked for me.
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!
oh my god! thank you man! this is awesome.
you saved my life with this snippet!!! thanks!!!!
No problem anytime 🙂