12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Apr 25, 2022

Get WooCommerce Product Gallery Count

Sridhar Katakam

Looking to get a count of the number of images in WooCommerce product gallery for individual products?

Here’s a handy function for it:

<?php 

function wpdd_get_product_gallery_count() {
    // Get the current product object from the product ID
    $product = wc_get_product( get_the_ID() );
    
    // if $product is not an object, return 0
    if ( $product === false ) {
        return 0;
    }
    
    // Get the product gallery attachment IDs
    $attachment_ids = $product->get_gallery_image_ids();

    // if there are no product gallery images, return 0
    if ( ! $attachment_ids ) {
        return 0;
    }
    
    // Return the number of gallery images
    return count( $attachment_ids );
}

Usage:

<?php 

echo wpdd_get_product_gallery_count();
// 4

?>

Practical Example:

If you are using Oxygen Builder with OxyExtrasCarousel Builder component for showing the product gallery images as a carousel, this function could be used to ensure that the Section in which the component is present is output only if there are say, at least 2 images.

Here’s how:

In the Oxygen Template that applies to singular products, add (if not already present) a Section and inside that, Carousel Builder. From the component’s Carousel content dropdown, select “Woo product gallery”.

Next select the Section and click the Condition Settings icon → Set Conditions → Add your first condition.

Choose Dynamic Data → PHP Function Return value → Function Name: wpdd_get_product_gallery_count → INSERT.

Select > as the operator.

Enter 1 as the value to check against.

With this in place, the entire Section will be output only if there are a minimum of 2 product gallery images for the current product being viewed.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right