Search code examples
wordpresswoocommerceproducthook-woocommercecheckout

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


I am creating a landing page for the customers and with a specific products that has a category of landing-page.

I want the other products that is currently on the cart page to be removed when the category landing-page is present on the cart.

Here's the snippet. Right now, it removes all the products in it because of the $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
    }
}

Any advice?


Solution

  • You can use WC_Cart::remove_cart_item() opposite WC_Cart::empty_cart()

    So you get:

    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 );