A client needed to disable all shipping methods but Local Pickup for a certain variation ID. This may come useful if you’re looping through the variations on the cart/checkout page (check if variation ID is in the cart for example), so here you go!
Where to Find Variation IDs – WooCommerce
WooCommerce Find Variation IDs
PHP Snippet: Disable Shipping Rates if Variation ID is in the Cart – WooCommerce
/**
* @snippet WooCommerce Disable Shipping Rates if Variation ID @ Cart
* @how-to Get tutoraspire.com FREE
* @sourcecode https://tutoraspire.com/?p=17436
* @author Tutor Aspire
* @compatible WooCommerce 3.4.4
*/
add_filter( 'woocommerce_package_rates', 'tutoraspire_unset_woocommerce_shipping_methods_when_ids', 10 ,2 );
function tutoraspire_unset_woocommerce_shipping_methods_when_ids ( $rates, $package ) {
// loop through the cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
// if product variation id @ Cart, disable all but Local Pickup
if( $_product->variation_id == 3102 || $_product->variation_id == 3103 || $_product->variation_id == 3093 || $_product->variation_id == 3094 ) {
$local_pickup = $rates['local_pickup'];
$rates = array();
$rates['local_pickup'] = $local_pickup;
}
}
return $rates;
}