如何将当前图像编号添加到 WooCommerce 中的每个产品图库图像?

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

我正在寻找一种在我的 WooCommerce 商店中显示产品图片计数器的解决方案。例如,如果我的产品有 5 张照片,我想在每张照片下方显示:1/5、2/5、3/5 等。

首先我想到的是CSS和jQuery。例如,我可以将 CSS 与第 nth-child(1)、nth-child(2) 添加到 10 或 20,例如:

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/";
}

然后使用 JS 我可以在 FIGURE 容器中捕获子 DIV 的数量,并在我的代码后使用 CSS.

显示它

但也许还有其他最简单的方法可以在 functions.php 或图库 PHP 文件中使用某些循环?有什么想法可以实现吗?

试试这个:

// 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

}

代码已经过测试并且可以工作。将它添加到您的活动主题 functions.php.

最后添加此 CSS 规则:

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

将其添加到活动主题的样式表中。

结果