WooCommerce: Check if Products in Cart Have a Specific Tag and Remove Them If They Can't Be Shipped

Blog

Posted by Nuno Marques on 20 Apr 2020

Tutorial

Check if Products in Cart Have a Specific Tag: #bottle-wine

Initially, you experimented with a lengthy AJAX-based solution, which proved to be inefficient. After refining your approach, you discovered a more streamlined solution that effectively addresses the issue.

/**
 * @snippet       Check if products in cart have a specific tag: #bottle-wine
 * @sourcecode    <https://stackoverflow.com/questions/53346384/avoid-checkout-for-specific-products-on-specific-country-in-woocommerce>
 * @sourcecode    <https://stackoverflow.com/questions/48795558/disable-shipping-for-specific-products-based-on-country-in-woocommerce>
 */

add_action( 'woocommerce_before_calculate_totals', 'checking_and_removing_items', 10, 1 );
function checking_and_removing_items( $cart ) {
    if( !is_checkout() && !is_cart() ) return;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $customer_shipping_country = WC()->customer->get_shipping_country();

    if( empty($customer_shipping_country) ){
        $package = WC()->shipping->get_packages()[0];
        if( ! isset($package['destination']['country']) ) return;
        $customer_shipping_country = $package['destination']['country'];
    }

    // Only for non-Belgian customers
    if( $customer_shipping_country == 'BE' ) return;

    // Iterate through each cart item
    $found = false;
    foreach( $cart->get_cart() as $cart_item_key => $cart_item )
        if( has_term( array('bottle-wine'), 'product_tag', $cart_item['product_id'] ) ) {
            $found = true;
            $cart->remove_cart_item( $cart_item_key ); // Remove item
        }

    if( $found ){
         // Custom notice
         wc_clear_notices();
         wc_add_notice('Wine products are not shippable to your country and have been removed', 'error');
    }
}

Conclusion

By implementing this solution, you can effectively manage product restrictions based on specific tags and shipping constraints, providing a seamless and tailored shopping experience for your WooCommerce customers.

This post was tagged in: