【问题标题】:Auto assign shipping class to WooCommerce Variation based on attribute根据属性自动将运输类别分配给 WooCommerce 变体
【发布时间】:2020-10-08 13:29:50
【问题描述】:

我有一些具有尺寸属性和 3 种变体(小、中、大)的产品。我还有 3 个运输等级,每种尺寸一个。

任何产品的小型变体都将使用小型产品运输类别,中型和大型也是如此。

我可以手动将每个运输类别分配给每个变体,但在这种情况下它很耗时、容易出错并且是多余的(创建大型变体,然后分配大型运输类别)

有什么方法可以将运输类别与特定变体联系起来,所以当我创建变体时,它会附带已分配的相应运输类别?

【问题讨论】:

    标签: php wordpress woocommerce shipping-method product-variations


    【解决方案1】:

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

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

    代码:

    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 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 2018-03-26
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      相关资源
      最近更新 更多