Search code examples
phpwordpressimagewoocommerceproduct

How to remove product thumbnail if only one image is added to product WooCommerce


Good I was wondering if i could remove product thumbnail from single product page is product has only one image (i.e the product image only).. So that when user are viewing the product with only one image, they dont need to see the thumbnail but products with product image and Product gallery images, the thumbnail can show up.

Is there a way to achieve this?

I have tried the below but didn't work for me (though the code is to remove the thumbnail entirely);

function remove_gallery_thumbnail_images() {
    if ( is_product() ) {
        remove_action( 'woocommerce_product_thumbnails', 'woocommerce_show_product_thumbnails', 20 );
    }
}
add_action('loop_start', 'remove_gallery_thumbnail_images');

How can i achieve this? disable the thumbnail if product has only one image but display thumbnails if product has multiple images.

Any help is very welcome.


Solution

  • Normally woocommerce doesn't show the gallery when there is no thumbnails in it.

    In your case, you can try to use the following:

    add_action( 'woocommerce_product_thumbnails', 'enable_gallery_for_multiple_thumbnails_only', 5 );
    function enable_gallery_for_multiple_thumbnails_only() {
        global $product;
    
        if( ! is_a($product, 'WC_Product') ) {
            $product = wc_get_product( get_the_id() );
        }
    
        if( empty( $product->get_gallery_image_ids() ) ) {
            remove_action( 'woocommerce_product_thumbnails', 'woocommerce_show_product_thumbnails', 20 );
        }
    }
    

    Or if the image is included as a thumbnail in the gallery you can replace in the function:

    if( empty( $product->get_gallery_image_ids() ) ) {
    

    by the following line:

    if( sizeof( $product->get_gallery_image_ids() ) == 1 ) {
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.


    You can also hide the gallery with an inline CSS:

    add_action( 'woocommerce_before_single_product_summary', 'enable_gallery_for_multiple_thumbnails_only', 5 );
    function enable_gallery_for_multiple_thumbnails_only() {
        global $product;
    
        if( ! is_a($product, 'WC_Product') ) {
            $product = wc_get_product( get_the_id() );
        }
    
        if( empty( $product->get_gallery_image_ids() ) ) {
            echo '<style> ol.flex-control-thumbs { display:none; } </style>';
        }
    }
    

    Or if the image is included as a thumbnail in the gallery you can replace in the function:

    if( empty( $product->get_gallery_image_ids() ) ) {
    

    by the following line:

    if( sizeof( $product->get_gallery_image_ids() ) == 1 ) {
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.

    All this works on themes that doesn't make related customizations.