如果 WooCommerce 结账时存在某些产品类别,请删除其他产品

Remove other products if certain product category is present on WooCommerce checkout

我正在为客户创建一个登陆页面,并使用类别为 landing-page 的特定产品。

当类别 landing-page 出现在购物车中时,我希望删除当前在购物车页面上的其他产品。

这是片段。现在,由于 $woocommerce->cart->empty_cart().

,它删除了其中的所有产品
add_action('woocommerce_checkout_before_customer_details', 'check_if_landing_page_category_is_on_cart');
function check_if_landing_page_category_is_on_cart() {
    
    global $woocommerce;
    $categories   = array('landing-page');
    $has_category = false;
    
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Check for product categories
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            
            $woocommerce->cart->empty_cart();
            $has_category = true;
            break;
        }
    }
    
    if ( $has_category ) { 
        ?>
            <style>
                .coupon-form {
                    display: none;
                }
            </style>
        <?php
    }
}

有什么建议吗?

您可以使用WC_Cart::remove_cart_item() opposite WC_Cart::empty_cart()

所以你得到:

function action_woocommerce_checkout_before_customer_details() {
    // Add categories. Multiple can be added, separated by a comma
    $categories = array( 'landing-page' );
    
    // Initialize
    $cart_item_keys = array();
    $has_category = false;
    
    // WC Cart NOT null
    if ( ! is_null( WC()->cart ) ) {
        // Loop through cart items
        foreach ( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
            // Get product id
            $product_id = $cart_item['product_id'];
            
            // NOT certain category     
            if ( ! has_term( $categories, 'product_cat', $product_id ) ) {
                // Push to array
                $cart_item_keys[] = $cart_item_key;
            } else {
                $has_category = true;
            }
        }
        
        // NOT empty & has category is true
        if ( ! empty ( $cart_item_keys ) && $has_category ) {
            // Loop through all cart item keys that do not contain the category
            foreach ( $cart_item_keys as $cart_item_key ) {
                // Remove product from cart
                WC()->cart->remove_cart_item( $cart_item_key ); 
            }
        }
    }
}
add_action( 'woocommerce_checkout_before_customer_details', 'action_woocommerce_checkout_before_customer_details', 10, 0 );