Auto assign shipping class to WooCommerce Variation based on attribute

549 views Asked by At

I have some products with a Size attribute and 3 Variations (small, medium, large). I also have 3 shipping classes, one for each Size.

Any product's Small variation will use the Small Product Shipping Class, and the same goes for Medium and Large.

I can assign each shipping class to each variation manually but it's time-consuming, prone to errors, and redundant in this case (create a Large variation, then assign a Large shipping class)

Is there any way to connect a shipping class to a specific variation, so when I create the variation it comes with the corresponding shipping class already assigned?

1

There are 1 answers

0
LoicTheAztec On BEST ANSWER

The following code should do the trick, auto adding To Product variations, the shipping class ID based on product attribute "Size" term value assigned to the variation.

It requires to have the same terms for Size product attribute and for shipping classes terms too ("Small", "Medium" and "Large" in your case)

The code:

add_action( 'woocommerce_save_product_variation', 'auto_add_shipping_method_based_on_size', 10, 2 );
function auto_add_shipping_method_based_on_size( $variation_id, $i ){
    // Get the WC_Product_Variation Object
    $variation = wc_get_product( $variation_id );

    // If the variation hasn't any shipping class Id set for it
    if( ! $variation->get_shipping_class_id() ) {
        // loop through product attributes
        foreach( $variation->get_attributes() as $taxonomy => $value ) {
            if( 'Size' === wc_attribute_label($taxonomy) ) {
                // Get the term name for Size set on this variation
                $term_name = $variation->get_attribute($taxonomy);

                // If the shipping class related term id exist
                if( term_exists( $term_name, 'product_shipping_class' ) ) {
                    // Get the shipping class Id from attribute "Size" term name
                    $shipping_class_id = get_term_by( 'name', $term_name, 'product_shipping_class' )->term_id;

                    // Set the shipping class Id for this variation
                    $variation->set_shipping_class_id( $shipping_class_id );
                    $variation->save();
                    break; // Stop the loop
                }
            }
        }
    }
}

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