[英]Woocommerce Product allready in cart
I have this code to show when the product is already in the cart I need it to show the quantity of the product also.我有这个代码来显示产品何时已经在购物车中我还需要它来显示产品的数量。
add_filter( 'woocommerce_product_add_to_cart_text', 'wcpt_modify_add_to_cart_text', 9999, 2 );
function wcpt_modify_add_to_cart_text( $text, $product ) {
// if cart is empty return 'Add to Quote'
if ( WC()->cart->is_empty() ) return 'Add to Quote';
// otherwise loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
$qty = $cart_item['quantity'];
// if cart contains current product ID return its quantity
if ( $product->get_id() == $product_id ) {
return $qty . ' - Already Added';
}
}
// if the cart is not empty but the product is not in the cart...
return 'Add to Quote';
}
UPDATED CODE ABOVE UPDATED WITH HOOKS ASWELL The Code Above works wonders thanks to @businessbloomer the only problem now is that I have to refresh the page to see anything上面的更新代码也用钩子更新了上面的代码由于@businessbloomer而产生了奇迹现在唯一的问题是我必须刷新页面才能看到任何东西
Code is a bit messy, this revised version should work.代码有点乱,这个修改后的版本应该可以。 I added some inline comments to explain each new section:我添加了一些内联注释来解释每个新部分:
add_filter( 'woocommerce_product_add_to_cart_text', 'wcpt_modify_add_to_cart_text', 9999, 2 );
function wcpt_modify_add_to_cart_text( $text, $product ) {
// if cart is empty return 'Add to Quote'
if ( WC()->cart->is_empty() ) return 'Add to Quote';
// otherwise loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
$qty = $cart_item['quantity'];
// if cart contains current product ID return its quantity
if ( $product->get_id() == $product_id ) {
return $qty . ' - Already Added';
}
}
// if cart is not empty but product is not in the cart...
return 'Add to Quote';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.