How To: Know If The Current Post Has More Than One Images Attached To It?
Few days back I’m working on a blog site of my friend and he’s using Gallery WordPress built-in Shortcode to display attached images in theme single/post page but he don’t want to display any additional image attached if it only contain single image or simply for featured image alone, and I came to the rescue (char), so the idea here is we simply check if there’s two or more images attached then display it or otherwise don’t display anything because mostly it is mean for featured image.
Let’s get started
Code
Paste this code into your current theme’s functions.php file.
/*
* @desc Check if the current post has one or more images attached
* @return TRUE on success otherwise false on failure or if it only single image or less
*/
function has_images_attached( $post_id = null ) {
if( empty( $post_id ) )
return;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $post_id,
'posts_per_page' => -1,
);
$images_attached = get_posts( $args );
$post_count = count( $images_attached );
if( $post_count )
return true;
return false;
}
Theme File
Paste this code into your current theme’s single.php or page.php file
if( has_images_attached( get_the_ID() ) ) {
// two or more images attached
} else {
// no or only has single image attached
}
That’s it happy coding ^_^