WooCommerce allow one product in cart and limit the cart to max one product

WooCommerce allow one product in cart and limit the cart to max one product 

 




> Woocommerce allow one product in cart


function woo_cart_ensure_only_one_item( $cart_contents ) {
return array( end( $cart_contents ) );
}
add_filter( 'woocommerce_cart_contents_changed', 'woo_cart_ensure_only_one_item' );

> Limit the Cart to Max One Product – WooCommerce

Using a custom function hooked in woocommerce_add_to_cart_validation filter hook, will allow you to restrict the cart items to 1 max and to display a custom message when this limit is exceeded:

// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_six_items_allowed_add_to_cart', 10, 3 );

function only_six_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;

if( $cart_items_count >= 1 || $total_count > 1 ){
// Set to false
$passed = false;
// Display a message
wc_add_notice( __( "You can’t have more than 1 items in cart", "woocommerce" ), "error" );
}
return $passed;
}

Using a custom function hooked in woocommerce_update_cart_validation filter hook, will allow you to control the cart items quantities update to your 1 cart items limit and to display a custom message when this limit is exceeded:

// Checking and validating when updating cart item quantities when products are added to cart
add_filter( 'woocommerce_update_cart_validation', 'only_six_items_allowed_cart_update', 10, 4 );
function only_six_items_allowed_cart_update( $passed, $cart_item_key, $values, $updated_quantity ) {

$cart_items_count = WC()->cart->get_cart_contents_count();
$original_quantity = $values['quantity'];
$total_count = $cart_items_count - $original_quantity + $updated_quantity;

if( $cart_items_count > 1 || $total_count > 1 ){
// Set to false
$passed = false;
// Display a message
wc_add_notice( __( "You can’t have more than 1 items in cart", "woocommerce" ), "error" );
}
return $passed;
}

Video tutorial: 

WooCommerce allow one product in cart and limit the cart to max one product WooCommerce allow one product in cart and limit the cart to max one product Reviewed by Md Shahinur Islam on July 25, 2022 Rating: 5

No comments:

Powered by Blogger.