Search code examples
phpwordpresswoocommerceadvanced-custom-fieldscart

Get a custom field in WooCommerce cart for variable products too using ACF


In WooCommerce, I am using Advanced Custom Fields plugin to display a custom field(image) called 'product_cart_image' which replaces the default image of a product in cart. The code is working for simple products but it's not working for variable products. For these I get the default image.

The following code goes in cart.php template file:

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 );
    $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); 
    ?>
    <span class="product-thumbnail">
    <?php
    $product_image      = $_product->get_image();
    $product_cart_image = get_field('product_cart_image', $_product->get_id());

    if ( ! empty ( $product_cart_image ) ) {
        $product_image = wp_get_attachment_image( $product_cart_image['ID'] );
    }

    $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $product_image, $cart_item, $cart_item_key );

    if ( ! $product_permalink ) {
        echo $thumbnail;
    } else {
        printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); 
    }
    ?>
    </span>
    <?php
}

How can I make it work for variable products too?


Solution

  • When a variable product is added to cart, for a cart item cart you need to get the variable product ID instead of the variation ID, so you will replace the following line:

    $product_cart_image = get_field('product_cart_image', $_product->get_id());
    

    by:

    $product_cart_image = get_field('product_cart_image', $cart_item['product_id']);
    

    Now it should work… So in your code:

    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 );
        $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); 
        ?>
        <span class="product-thumbnail">
        <?php
        $product_image      = $_product->get_image();
        $product_cart_image = get_field('product_cart_image', $cart_item['product_id']);
    
        if ( ! empty ( $product_cart_image ) ) {
            $product_image = wp_get_attachment_image( $product_cart_image['ID'] );
        }
    
        $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $product_image, $cart_item, $cart_item_key );
    
        if ( ! $product_permalink ) {
            echo $thumbnail;
        } else {
            printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); 
        }
        ?>
        </span>
        <?php
    }