Allow free shipping on minimum quantity for only one product category exclusively in WooCommerce

I want to add free shipping if there is in cart at least 5 items (products) exclusively from "stickers" category, but not if there are also products from other categories. The following code works handling "stickers" category, but it offers free shipping when there are at least 5 items from "stickers" category and items from other categories in cart: function filter_woocommerce_shipping_free_shipping_is_available( $is_available, $package, $shipping_method ) { /* SETTINGS free shipping TOTEBAG ONLY */ // Set categories $specific_categories = array ( 'stickers' ); // Set minimum $minimum = 5; /* END settings */ // Counter $count = 0; // Loop through cart items foreach( $package['contents'] as $cart_item ) { // If product categories is found if ( has_term( $specific_categories, 'product_cat', $cart_item['product_id'] ) ) { $count += $cart_item['quantity']; } } // Condition if ( $count >= $minimum ) { $notice = __( 'Free Shipping', 'woocommerce' ); $is_available = true; } else { $notice = __( 'NO Free Shipping', 'woocommerce' ); $is_available = false; } // Display notice if ( isset( $notice ) ) { wc_add_notice( $notice, 'notice' ); } // Return return $is_available; } add_filter( 'woocommerce_shipping_free_shipping_is_available', 'filter_woocommerce_shipping_free_shipping_is_available', 10, 3 ); Can somebody help to adjust the PHP code to make other products pay for shipping?

Comment (1)

Jese Leos

August 10, 2024

Verified user

You simply need to count items from "stickers" category and from other categories, to allow free shipping when there are exclusively at least 5 items from "stickers" category: add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_shipping_available_for_5_stickers_min', 10, 3 ); function free_shipping_available_for_5_stickers_min( $is_available, $package, $shipping_method ) { $allowed_terms = array ( 'stickers' ); // Here define the allowed category(ies) $minimum = 5; // Define the minimum number of required items (quantity) $allowed_count = $others_count = 0; // Initializing variables (counters) // Loop through cart items foreach( $package['contents'] as $item ) { if ( has_term($allowed_terms, 'product_cat', $item['product_id']) ) { $allowed_count += $item['quantity']; // Count allowed items } else { $others_count += $item['quantity']; // Count other items } } if ( $allowed_count >= $minimum && $others_count === 0 ) { $notice = __( 'Free Shipping', 'woocommerce' ); $is_available = true; } else { $notice = __( 'No Free Shipping available', 'woocommerce' ); $is_available = false; } // Display notice if ( isset($notice) ) { wc_add_notice( $notice, 'notice' ); } return $is_available; } Code goes in functions.php file of your child theme (or in a plugin). It should work as expected.

You’ll be in good company