请勿在WooCommerce中同时购买免费和付费产品



我的意图是WooCommerce不能同时购买免费和付费产品。

如果购物篮中有免费产品或零价格产品,则应将所有付费产品从购物篮中移除或相反的情况

总之,付费产品和免费产品不能同时订购。

下面的代码是我想要工作的近似,但它并没有完全回答我的问题。我该如何处理?

add_action( 'template_redirect', 'test_cart_values' );
function test_cart_values(){
$ic_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$price = WC()->cart->get_product_price( $product );
if ( $price == 0 || $price === '') {
$ic_cart = true;
break;  
}
}
if ( $ic_cart ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$price = WC()->cart->get_product_price( $product );

if ( $price != 0 || $price !== '') {
WC()->cart->remove_cart_item( $cart_item_key );     
break;
}
}
}
}

您可以将woocommerce_add_to_cart钩子与template_redirect钩子相对使用。

将产品添加到购物车时,将当前产品价格与购物车中产品的价格进行比较。如果价格不匹配,从购物车中删除产品,这是通过一个循环,以便它应用于购物车中的所有产品。

得到:

function action_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// Get current product
$current_product = wc_get_product( $product_id );
// Get current product price
$current_product_price = $current_product->get_price();
// Initialize
$is_free = false;
$notice = false;
// When current product price = 0
if ( $current_product_price == 0 ) {
// Make true
$is_free = true;
}
// Loop through cart contents
foreach ( WC()->cart->get_cart_contents() as $item_key => $cart_item ) {
// Get price
$product_price = $cart_item['data']->get_price();
// Product price is NOT equal to 0 and current product is free
if ( $product_price != 0 && $is_free ) {
// Remove product from cart
WC()->cart->remove_cart_item( $item_key );
// Make true
$notice = true;
// Product price is equal to 0 and current product is NOT free
} elseif ( $product_price == 0 && ! $is_free ) {
// Remove product from cart
WC()->cart->remove_cart_item( $item_key );
// Make true
$notice = true;
}
}
// Optionaly displaying a notice
if ( $notice ) {
wc_add_notice( __( 'Some products have been removed from the cart because free and paid products cannot be bought together', 'woocommerce' ), 'notice' );
}
}
add_action( 'woocommerce_add_to_cart', 'action_woocommerce_add_to_cart', 10, 6 );

最新更新