简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM