[英]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.在 WooCommerce 中,我使用高级自定义字段插件来显示一个名为“product_cart_image”的自定义字段(图像),它替换了购物车中产品的默认图像。 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:以下代码在cart.php
模板文件中:
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:将可变产品添加到购物车时,对于购物车商品购物车,您需要获取可变产品 ID 而不是变体 ID,因此您将替换以下行:
$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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.