Show “Local Pickup” shipping method only for specific Woocommerce product categories [closed]

I have some products categories on my website where customers can collect from my store, so I need to add local pickup as a shipping method. I have added local pickup but it shows a checkbox at the checkout page for customers to select normal shipping or local pickup. What i need is, when a customer adds a products to the cart that is on the “x” category, show them normal shipping cost and local pickup so they can select whichever is convenient for them, and other products only with normal shipping cost. I don’t want to show local pickup for other categories.

1 Answer
1

The following will only show “Local pickup” shipping method for specific product categories in cart:

add_action( 'woocommerce_package_rates','show_hide_local_pickup_shipping_methods', 10, 2 );
function show_hide_local_pickup_shipping_methods( $rates, $package ) {

    // HERE BELOW your product categories in the array
    $categories = array( 't-shirts', 'hat' );

    $term_found = false;

    // Loop through cart items
    foreach( $package['contents'] as $cart_item ){
        if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $term_found = true;
            break;
        }
    }

    // Loop through shipping methods
    foreach( $rates as $rate_key => $rate ) {
        if( 'local_pickup' === $rate->method_id && ! $term_found ) {
            unset($rates[$rate_key]);
        }
    }
    return $rates;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Note: You may be need to refresh shipping methods, emptying the cart and going to shipping settings/ then disable / save and re-enable / save any shipping methods.

Leave a Comment