php - Woo Commerce 仅允许一种类型的产品变体
问题描述
我已经使用 woo commerce 构建了一个可步进的购物车结账功能,它允许将 3 种类型的产品添加到购物车中。类型 1 可以有两种变体,类型 2 只是一种产品,但类型 3 是会员类型(我只能允许将其中一种添加到购物车)
我的产品添加到购物车链接 www.example.com/cart-2/step3/?add-to-cart=1455
我已添加到我的 function.php 文件中的内容,但不限制用户向购物车添加多个成员资格时的内容。当前的会员类别标签是“会员”
add_action('woocommerce_add_to_cart', 'custom');
function custom() {
$cart = WC()->cart->get_cart();
print_r($cart);
$first_id = 1455; // ID of the first product
$second_id = 1456; // ID of the second product
$third_id = 1457; // ID of the third product
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item) {
// Check if the product is in cart
$Item_inCart = $cart_item['data']->get_id();
if ( ($Item_inCart == $first_id) && ($Item_inCart == $second_id) || ($Item_inCart == $third_id) ) {
print_r($first_id);
$prod_to_remove = '';
if( $prod_to_remove == $third_id || $prod_to_remove == $second_id) {
// Get it's unique ID within the Cart
$prod_unique_id = WC()->cart->generate_cart_id( $third_id );
$prod_unique_id2 = WC()->cart->generate_cart_id( $second_id );
// Remove it from the cart by un-setting it
unset( WC()->cart->cart_contents[$prod_unique_id] );
unset( WC()->cart->cart_contents[$prod_unique_id2] );
}
}
if ( ($Item_inCart == $second_id) && ($Item_inCart == $first_id) || ($Item_inCart == $third_id) ) {
print_r($second_id);
$prod_to_remove = '';
if( $prod_to_remove == $first_id || $prod_to_remove == $third_id) {
// Get it's unique ID within the Cart
$prod_unique_id = WC()->cart->generate_cart_id( $first_id );
$prod_unique_id2 = WC()->cart->generate_cart_id( $third_id );
// Remove it from the cart by un-setting it
unset( WC()->cart->cart_contents[$prod_unique_id] );
unset( WC()->cart->cart_contents[$prod_unique_id2] );
}
}
if ( ($Item_inCart == $third_id) && ($Item_inCart == $first_id) || ($Item_inCart == $second_id) ) {
print_r($third_id);
$prod_to_remove = '';
if( $prod_to_remove == $second_id || $prod_to_remove == $first_id) {
// Get it's unique ID within the Cart
$prod_unique_id = WC()->cart->generate_cart_id( $second_id );
$prod_unique_id2 = WC()->cart->generate_cart_id( $first_id );
// Remove it from the cart by un-setting it
unset( WC()->cart->cart_contents[$prod_unique_id] );
unset( WC()->cart->cart_contents[$prod_unique_id2] );
}
}
}
}
感谢您的任何帮助