Checkout with a single product: verify if ANY product is in the cart, and give error

試著忘記壹切 提交于 2019-12-02 03:42:14

Don't make changes directly in woocommerce core file because when you update plugin, might your code lost.

Add following code into functions.php and it will add only one product into cart:

add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_cart_item_data_custom' );

function woocommerce_add_cart_item_data_custom( $cart_item_data ) {

    global $woocommerce;
    if($woocommerce->cart->cart_contents_count > 0){
         wc_add_notice(
                     __( 'You cannot add another product to your cart.', 'woocommerce' ));

                return false;
    }
}

There is a filter/hook that runs before an item is added to the cart as each product goes through validation before it is added.

So when validating a product, we can check if the item if there are already items in the cart and clears those (if the current item is able to be added) and adds an error message.

/**
 * When an item is added to the cart, remove other products
 */
function so_27030769_maybe_empty_cart( $valid, $product_id, $quantity ) {

    if( ! empty ( WC()->cart->get_cart() ) && $valid ){
        WC()->cart->empty_cart();
        wc_add_notice( 'Whoa hold up. You can only have 1 item in your cart', 'error' );
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'so_27030769_maybe_empty_cart', 10, 3 );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!