Prevent Duplicate Items in Cart
Blocks adding a product to the cart if it is already present, showing a friendly notice and redirecting the customer to the cart instead.
PHPby SnipCraft
php
<?php
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
add_filter( 'woocommerce_add_to_cart_validation', 'scseed_prevent_duplicate_cart_items', 10, 2 );
function scseed_prevent_duplicate_cart_items( $passed, $product_id ) {
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( (int) $cart_item['product_id'] === (int) $product_id ) {
wc_add_notice(
sprintf(
/* translators: %s: link to the cart page */
__( 'This item is already in your cart. <a href="%s">View cart</a>', 'woocommerce' ),
esc_url( wc_get_cart_url() )
),
'error'
);
return false;
}
}
return $passed;
}#cart#checkout#duplicates#ux#woocommerce