Get data from product in WooCommerce cart for ACF image field

Viewed 122

Every product in my shop has an ACF image field that displays a t-shirt image associated with the product (event).

Now I need customers to see this image when they checkout. I decided to create a shortcode and add it somewhere on the checkout page.

I can't figure out how to get the ACF image field from the item in cart?

So far trying to use this code I put into functions.php. Any idea?

function wpb_demo_shortcode() { 
 

    $product_id = $cart_item['product_id'];
    $image = get_field('tenue', $product_id);
    $size = 'full'; // (thumbnail, medium, large, full or custom size)
        if( $image ) {
            return wp_get_attachment_image( $image, $size );
        }
} 
// register shortcode
add_shortcode('tenue-shortcode', 'wpb_demo_shortcode');

Note: We run a setting that there can be only one product in cart.

1 Answers

To get 1 product ID from the shopping cart you can use WC()->cart->get_cart() and break in a foreach loop

So you get:

function wpb_demo_shortcode() {
    // WC Cart
    if ( WC()->cart ) {
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            $product_id = $cart_item['product_id'];
            break;
        }
        
        // Isset
        if ( isset ( $product_id ) ) {
            $image = get_field( 'tenue', $product_id );
            $size = 'full'; // (thumbnail, medium, large, full or custom size)
            
            if ( $image ) {
                return wp_get_attachment_image( $image, $size );
            }
        }
    }
} 
// register shortcode
add_shortcode( 'tenue-shortcode', 'wpb_demo_shortcode' ); 
Related