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 Featured Products in WooCommerce?

Online store owners use featured products to highlight specific items, giving them special attention and visibility. If you want to hide shipping only for featured products then it can be easily done with the following code.

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

function ts_custom_shipping_methods($rates, $package) {
    // Check if any product in the cart is a featured product
    $has_featured_product = false;
    foreach ($package['contents'] as $cart_item) {
        $product = wc_get_product($cart_item['product_id']);
        if ($product && $product->is_featured()) {
            $has_featured_product = true;
            break;
        }
    }

    // Adjust shipping methods based on the presence of featured products
    if ($has_featured_product) {
        // If featured products are present, hide all shipping methods except free shipping
        $rates = ts_hide_shipping_when_free_is_available($rates);
    }

    return $rates;
}

// Function to hide shipping methods when free shipping is available
function ts_hide_shipping_when_free_is_available($rates) {
    $free = array();
    foreach ($rates as $rate_id => $rate) {
        if ('free_shipping' === $rate->get_method_id()) {
            $free[$rate_id] = $rate;
        }
    }
    return !empty($free) ? $free : $rates;
}

Output

In the below image, it is shown that two of the products are added as featured products.

How to Enable or Disable Shipping Based on Featured Products in WooCommerce? - Tyche Softwares

When featured products are added to cart, it displays only Free shipping option and hides the other shipping methods.

How to Enable or Disable Shipping Based on Featured Products in WooCommerce? - Tyche Softwares

When products other than featured products are added, then it will show all the available shipping options as it is without making any changes as shown below.

How to Enable or Disable Shipping Based on Featured Products in WooCommerce? - Tyche Softwares

Alternatively, you can also hide shipping based on product tags in WooCommerce which will help you to assigns shipping costs based on the product tag items present in the cart.

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

Share It:

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