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!
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');
Shortcode to put in the preview card or single post.
[gallery_count]