我有一些具有尺寸属性和 3 种变体(小、中、大)的产品。我也有 3 个运输类别,每个尺寸一个。
任何产品的小型变体都将使用小型产品运输类别,中型和大型也是如此。
我可以手动将每个运输类别分配给每个变体,但在这种情况下它很耗时、容易出错并且是多余的(创建一个大型变体,然后分配一个大型运输类别)
有没有办法将运输类别连接到特定的变体,所以当我创建变体时,它已经分配了相应的运输类别?
我有一些具有尺寸属性和 3 种变体(小、中、大)的产品。我也有 3 个运输类别,每个尺寸一个。
任何产品的小型变体都将使用小型产品运输类别,中型和大型也是如此。
我可以手动将每个运输类别分配给每个变体,但在这种情况下它很耗时、容易出错并且是多余的(创建一个大型变体,然后分配一个大型运输类别)
有没有办法将运输类别连接到特定的变体,所以当我创建变体时,它已经分配了相应的运输类别?
以下代码应该可以解决问题,自动添加到产品变体,运输类 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 文件中。测试和工作。