0
votes

In WooCommerce, I have two shipping methods and two product attribute values for each variable product. Customer should select one of these attribute values to add the product to the cart.

I am trying to unset some shipping method based on the product attribute selected in the variation. For example if product attribute 'a' be selected then in the cart page only shipping method 1 should be displayed and if product attribute 'b' is selected, shipping method 2 should be displayed at the cart.

I don't know how should I do that.

1
Did you tried anything?mujuonly

1 Answers

0
votes

The following code will hide defined shipping methods based on the product variation product attribute terms, defined as settings, in the code below:

add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_variation_product_attribute', 10, 2 );
function 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:12'      => array('blue'),
        'local_pickup:13'   => array('black', 'white'),
    );

    // 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;
}

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

Refresh the shipping caches (required):

  1. This code is already saved on your function.php file.
  2. Check that the cart is empty…
  3. In a shipping zone settings, disable / save any shipping method, then enable back / save.

You are done and you can test it.