根据属性自动将运费 class 分配给 WooCommerce 变体

Auto assign shipping class to WooCommerce Variation based on attribute

我有一些产品具有尺码属性和 3 种款式(小号、中号、大号)。我还有 3 件 classes,每种尺码一件。

任何产品的 Small 变体都将使用 Small Product Shipping Class,Medium 和 Large 也是如此。

我可以手动将每个运费 class 分配给每个变体,但这很耗时,容易出错,而且在这种情况下是多余的(创建一个大变体,然后分配一个大运费 class )

有什么方法可以将运费 class 连接到特定变体,所以当我创建变体时,它会附带相应的运费 class 已经分配?

下面的代码应该可以解决问题,自动添加到产品变体,运输 class ID 基于分配给变体的产品属性“尺寸”术语值。

尺寸产品属性和运输 classes 条款也需要相同的条款(在您的情况下为“小”、“中”和“大”)

代码:

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

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。