Search code examples
phpjquerywordpresswoocommercehook-woocommerce

How to add current image number to each product gallery image in WooCommerce?


I am looking for a solution to show product images counter in my WooCommerce store. For example if my product has 5 photos I want to display under each photo: 1/5, 2/5, 3/5 etc.

First what I was thinking about was CSS and jQuery. For example I could add CSS with nth-child(1), nth-child(2) up to 10 or 20 like:

figure.woocommerce-product-gallery__wrapper div:nth-child(1):after {
    display: block !important;
    z-index: 100;
    color: #000;
    font-size: 14px;
    position: absolute;
    top: 20px;
    left: 20px;
    width: 20px;
    height: 30px;
    overflow: visible;
    content: "1/";
}

And then using JS I could catch number of child DIV's inside the FIGURE container and display it after my code using CSS.

But maybe there is other easiest way to use some loop in functions.php or gallery PHP file? Any ideas how to achieve that?


Solution

  • Try with this:

    // add the current number for each gallery image product
    add_action( 'wp_footer', 'add_number_for_each_gallery_image_product' );
    function add_number_for_each_gallery_image_product(){
    
       // only on the product page
       if ( ! is_product() ) {
          return;
       }
    
       ?>
       <script type="text/javascript">
          jQuery(function($){
             // count the gallery images
             var count = $('figure.woocommerce-product-gallery__wrapper .woocommerce-product-gallery__image').length;
             // for each gallery image adds the number
             $('figure.woocommerce-product-gallery__wrapper .woocommerce-product-gallery__image').each(function(index){
                index++;
                $(this).prepend('<span class="image_no">' + index + '/' + count + '</span>');
             });
          });
       </script>
       <?php
    
    }
    

    The code has been tested and works. Add it to your active theme's functions.php.

    Finally add this CSS rule:

    .flex-active-slide .image_no {
        position: absolute;
        background: #eeeeee;
        border-radius: 4px;
        padding: 5px 8px;
        color: #333;
        top: 12px;
        left: 12px;
        z-index:1;
    }
    

    Add it to your active theme's stylesheet.

    RESULT

    enter image description here