WooCommerce将产品图像自动添加到图库(如果图库为空)

问题描述 投票:1回答:1

在WooCommerce中,产品可以具有产品图像(单个图像)和产品库(多个图像)。

当我为产品选择产品图片时,我希望它也自动添加到产品库中。

一件重要的事情:它应该检查产品图像是否已经在图库中(因此图库不会有重复的图像)。

是否有用于此的php函数?

((我怀疑these lines of code可能有助于创建函数)

php wordpress woocommerce product gallery
1个回答
0
投票

我通过将产品图片添加到模板本身的Gallery数组中来解决。

<?php
    global $product;
    $attachment_ids = $product->get_gallery_image_ids();
    $product_image_id = $product->get_image_id();

    // Add product image to gallery if its not there.
    // (This will prevent empty galleries, and also prevent duplicate images)
    if (!in_array($product_image_id, $attachment_ids)) {
        array_unshift($attachment_ids, $product_image_id);
    }

    foreach ($attachment_ids as $attachment_id) :
        $attachment_full_url = wp_get_attachment_image_src($attachment_id, 'full')[0];
    ?>
        <div class="swiper-slide"><a href="<?php echo $attachment_full_url; ?>"><?php echo wp_get_attachment_image($attachment_id, 'woocommerce_single'); ?></a></div>
    <?php
    endforeach;
?>

但是,更好的解决方案是实际上将产品图像添加到图库本身,而不是使用模板代码来完成。

© www.soinside.com 2019 - 2024. All rights reserved.