Show How Many Images in Gallery

Description/Instructions

If you’re wanting to show how many images that a post has, great for classifieds or real estate sites, this is the snippet for you! To make it look good, add a container, then make it so it flows horizontal, then add an icon and a shortcode. Upload a camera icon and paste in the shortcode below. This will make it look good!

If this snippet helped, feel free to buy me a taco :)

function my_gallery_count_shortcode($atts) {
// Attributes
$atts = shortcode_atts(
array(
'post_id' => get_the_ID(), // Default to current post ID
),
$atts,
'gallery_count'
);

// Get the gallery field, which is a comma-separated string of image IDs or URLs
$gallery_string = get_post_meta($atts['post_id'], 'gallery', true);

// Check if the gallery field exists and is not empty
if ($gallery_string) {
// Split the string by comma to create an array of items
$images = explode(',', $gallery_string);

// Count the elements in the array
return count($images);
} else {
// Return zero if there are no images or the field doesn't exist
return '0';
}
}

// Register the shortcode with WordPress
add_shortcode('gallery_count', 'my_gallery_count_shortcode');

  • PHP
Copy Code

Instructions

Shortcode to put in the preview card or single post.

[gallery_count]

  • HTML
Copy Code

Let's Chat About this Snippet