在购物车对象中获取 WooCommerce 可变产品附件库 ID

Get WooCommerce variable product attachment gallery id in cart object

我这里有一个很奇怪的问题。我想使用第一个产品附件图库图像作为购物车页面中的产品缩略图。 所以我在 cart.php 中使用以下代码来获取图库附件 ID:

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
            $attachment_ids = $_product->get_gallery_attachment_ids();

奇怪的是,它在我的本地主机上运行良好(我的测试网站,woocommerce 版本是 2.6.8)。但是它无法在我的在线网站(woocommerce 版本为 3.1.2)上获取任何可变产品的数据。但是,它可以得到简单产品的正确数据。

我用print_r($_product)查看里面的数据,发现 WC_Product_Simple 对象具有正确的图库图像 ID,如下所示:[gallery_image_ids] => Array ( [0] => 1174 [1] => 1175 [2] => 1176 ) 但是 WC_Product_Variation 对象在数组中没有值:[gallery_image_ids] => Array ( )

我认为这是 Woocommerce 升级造成的。因为我的本地主机具有完全不同的 $_product.

对象结构

有谁知道另一种获取购物车页面中可变产品图库图像 ID 的方法吗?

  1. 方法 get_gallery_attachment_ids() 已弃用,在 WooCommerce 3 中已被 get_gallery_image_ids() 方法取代。
  2. WC_Product_variations 自己没有画廊,是父 WC_Product_Variable 有。

所以你可以这样管理它:

$product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$attachment_ids = $product->get_gallery_image_ids();
// For Product variations
if($product->is_type('variation') && empty($attachment_ids) ) {
    // Get the parent variable product
    $parent_product = wc_get_product( $product->get_parent_id() );
    $attachment_ids = $parent_product->get_gallery_image_ids();
    $image_id = $product->get_image_id(); // The variation main Image ID
}
// Testing output
print_r($attachment_ids);