Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Enable or Disable Shipping Based on Product Stock Status in WooCommerce?

As an online store owner, you can efficiently display shipping options based on the availability of products in stock with these simple code snippets. This code will hide the specific shipping method if any product in the cart has a stock quantity less than the specified minimum.

add_filter('woocommerce_package_rates', 'ts_all_products_shipping_methods', 10, 2);

function ts_all_products_shipping_methods($rates, $package) {
    $method_id = 'free_shipping'; // Set the shipping method ID
    $minimum_stock_quantity = 10; // Set the minimum stock quantity to show the flat rate

    // Check if any product in the cart has a stock quantity that allows shipping
    foreach ($package['contents'] as $cart_item) {
        $product = wc_get_product($cart_item['product_id']);
        $stock_quantity = $product->get_stock_quantity();

        if ($stock_quantity < $minimum_stock_quantity) {
            // Product stock quantity is less than the minimum, so unset the shipping method
            unset($rates[$method_id]);
            break; // Stop checking once we find a product with stock quantity below the minimum
        }
    }

    return $rates;
}

Output

Let’s have a look at the stock status of the products in the backend. One of the products has a stock status of less than 10 and the other product has a stock status greater than 10. Make a note that we have mentioned the minimum stock quantity to be 10. Now, if any product in the cart has a stock quantity below the specified minimum, the Free Shipping method will be hidden.

How to Enable or Disable Shipping Based on Product Stock Status in WooCommerce? - Tyche Softwares

When the products added to the cart have a product stock availability that is less than 10, then the ‘free shipping’ method is hidden from the shipping options.

How to Enable or Disable Shipping Based on Product Stock Status in WooCommerce? - Tyche Softwares

For products that have a stock availability count greater than 10, only for those products ‘free shipping’ method will be shown.

How to Enable or Disable Shipping Based on Product Stock Status in WooCommerce? - Tyche Softwares

Similar to the above customization, you can also enable shipping for certain products based on product quantity in WooCommerce which will help you control the shipping costs based on selected quantity.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Newest
Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x