Now it’s easy to customize the visibility of shipping methods based on the variation of product attributes selected by customers. This code modifies the available shipping rates based on the product attribute selected for color variations.
add_filter( 'woocommerce_package_rates', 'ts_hide_shipping_method_based_on_variation_product_attribute', 10, 2 ); function ts_hide_shipping_method_based_on_variation_product_attribute( $rates, $package ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // HERE define the Product Attibute taxonomy (starts always with "pa_") $taxonomy = 'pa_color'; // Example for "Color" // HERE define shipping method rate ID to be removed from product attribute term(s) slug(s) (pairs) in this array $data_array = array( 'flat_rate:4' => array('blue'), 'local_pickup:6' => array('black', 'red'), ); // Loop through cart items foreach( $package['contents'] as $cart_item ){ if( isset($cart_item['variation']['attribute_'.$taxonomy]) ) { // The product attribute selected term slug $term_slug = $cart_item['variation']['attribute_'.$taxonomy]; // Loop through our data array foreach( $data_array as $rate_id => $term_slugs ) { if( in_array($term_slug, $term_slugs) && isset($rates[$rate_id]) ) { // We remove the shipping method corresponding to product attribute term as defined unset($rates[$rate_id]); } } } } return $rates; }
Output
The below output shows that when a product attribute of the blue color is chosen, the code implies hiding the Flat rate shipping method.
And, when the customer chooses the red color attribute it hides the local pickup shipping method.
In addition, do you want to Hide the shipping method based on the quantity of the products? With the simple code snippets, you can also bring in the functionality of enabling shipping for certain products based on product quantity in WooCommerce.