phpwordpresswoocommercegallerycart

Get WooCommerce variable product attachment gallery id in cart object


I have a very weird problem here. I want to use the first product attachment gallery image as product thumbnail in cart page. So I use following code in cart.php to get gallery attachment 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();

The weird thing is, it worked perfectly on my localhost (my test website, which woocommerce version is 2.6.8). But it couldn’t get any data of the variable products on my online website (which woocommerce version is 3.1.2). However, it could get the correct data of simple products.

I use print_r($_product) to see the data in it, and find out that WC_Product_Simple Object has correct gallery image ids, as below: [gallery_image_ids] => Array ( [0] => 1174 [1] => 1175 [2] => 1176 ) But WC_Product_Variation Object has no value in the array: [gallery_image_ids] => Array ( )

I think it's caused by Woocommerce upgrade. Because my localhost has totally different object structure of $_product.

Does anyone know another way to get gallery image ids of variable product in cart page please?


Solution

    1. The method get_gallery_attachment_ids() is deprecated and has been replaced by get_gallery_image_ids() method in WooCommerce 3.
    2. WC_Product_variations don't have a gallery themselves, it's the parent WC_Product_Variable that have it.

    So you can manage it this way:

    $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);