如何将产品库中的随机图像显示为 Woocommerce 商店中的主要产品图像?

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

我的画廊里有 3 件彩色 T 恤。我随机想要这 3 张 T 恤图像中的一张作为我产品的主要图像。我希望它随机出现在产品页面和商店页面上。

我想我需要一个功能来实现此目的,我将把主图像保留为空,只将 3 张图像上传到图库。

此代码片段仅在商店页面上显示图库中的第一张图片,但由于它不是产品页面上的主图片,因此它显示为空。但我不想要第一张图片,我想要随机的。

function modify_woocommerce_product_get_image( $image, $product, $size, $attr ) {
    $image_ids = $product->get_gallery_image_ids();
    if( $image_ids ) {
        $image_ids = array_merge($image_ids, array($product->get_image_id()));
        $key = array_rand($image_ids);
        $id = $image_ids[$key];
        $image = wp_get_attachment_image( $id, $size, false, $attr );
    }
    return $image;
}
add_filter( 'woocommerce_product_get_image', 'modify_woocommerce_product_get_image', 99, 4 );
php wordpress woocommerce product
1个回答
0
投票

在数组上使用

shuffle()
尝试以下操作,以随机化图像 ID 的顺序:


function modify_woocommerce_product_get_image( $image, $product, $size, $attr ) {
    $image_ids = $product->get_gallery_image_ids();
    if( $image_ids ) {
        $image_ids = array_merge($image_ids, [$product->get_image_id()]);
        shuffle($image_ids);
        $image_id = reset($image_ids);
        $image = wp_get_attachment_image( $image_id, $size, false, $attr );
    }
    return $image;
}
add_filter( 'woocommerce_product_get_image', 'modify_woocommerce_product_get_image', 100, 4 );

应该可以。

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