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

问题描述:

我在这里有一个很奇怪的问题。我想在购物车页面中使用第一个产品附件图库图像作为产品缩略图。 在cart.php所以我用下面的代码获取图库附件ID:在购物车对象中获取WooCommerce变量产品附件图库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升级造成的。因为我的localhost有完全不同的$ _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);