我正在try 获得与简单和可变产品的每个行项目相关联的发货类别,然后找出哪种产品的成本最高,并收取仅扣除其余发货成本的费用.这是给WooCommerce的.
我所做的是-
- 添加了两个分区
- 增加了两个装运类别
- 为方法中的两个类添加了价格
- 将"按类"设置为计算方法
- 在产品变体中设置发货类别
编辑:到目前为止添加的代码.
add_filter('woocommerce_package_rates', 'custom_shipping_method_by_class', 10, 2);
function custom_shipping_method_by_class($rates, $package)
{
$class_costs = array();
foreach ($package['contents'] as $item) {
$product_id = $item['product_id'];
$product = wc_get_product($product_id);
if ($product instanceof WC_Product_Variable) {
foreach ($product->get_visible_children() as $variation_id) {
$term = wp_get_post_terms($variation_id, 'product_shipping_class');
if (!empty($term)) {
$term = reset($term);
$class_costs[$term->term_id] = max($class_costs[$term->term_id] ?? 0, $rates["{$term->term_id}:$variation_id"]->cost);
var_dump($class_costs); // I get 0 here although I the variation has the shipping class set and the class has an amount set too.
}
}
} else {
$term = wp_get_post_terms($product_id, 'product_shipping_class');
if (!empty($term)) {
$term = reset($term);
$class_costs[$term->term_id] = max($class_costs[$term->term_id] ?? 0, $rates["{$term->term_id}:$product_id"]->cost);
}
}
}
foreach ($rates as $rate_key => $rate) {
list($class_id, $product_id) = explode(':', $rate_key);
if (!array_key_exists($class_id, $class_costs) || $class_costs[$class_id] !== $rate->cost) {
unset($rates[$rate_key]);
}
}
return $rates;
}