add_action( 'woocommerce_check_cart_items', 'custom_prevent_free_and_non_free_shipping_products' );
function custom_prevent_free_and_non_free_shipping_products() {
// Check if the cart contains free shipping items
$has_free_shipping = false;
foreach( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_shipping_class() === 'free-shipping' ) {
$has_free_shipping = true;
break;
}
}
// Check if the cart contains non-free shipping items
$has_non_free_shipping = false;
foreach( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_shipping_class() !== 'free-shipping' ) {
$has_non_free_shipping = true;
break;
}
}
// If the cart contains both free and non-free shipping items, show an error message
if ( $has_free_shipping && $has_non_free_shipping ) {
wc_clear_notices();
wc_add_notice( __( 'You cannot mix free and non-free shipping items in the cart.', 'c2code' ), 'error' );
}
}
Jagdish Sarma Asked question September 12, 2023