以下方法允许在结帐时添加包裹的重量,方法是将要使用的包裹的重量除以购物车物品。这样,购物车总重量也包括箱子重量,并且运输选项可以反映实际订单总重量的正确价格。
add_action( 'woocommerce_before_calculate_totals', 'add_custom_weight', 10, 1 );
function add_custom_weight( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
//box sizes (kg)
$Small_envelope = 0.095;
$Medium_envelope = 0.11;
$Large_envelope = 0.2;
$Small_box = 0.4;
$Medium_box = 0.6;
//
循环浏览购物车商品并获取订单中商品的总高度和最大宽度,以进行额外检查以应用适当的框(如果需要)
foreach(WC()->cart->get_cart() as $cart_item ) {
$total_height += $cart_item['data']->get_height() * $cart_item['quantity'];
$temp_width = $cart_item['data']->get_width();
if ($temp_width > $max_width){
$max_width = $temp_width; }
$cart_items_qty += $cart_item['quantity'];
}
//Check which box should be used based on total order height
if( $total_height <= 2.7 && $max_width < 19) {
$extra_weight = $Small_envelope;
}
if( $total_height > 2.7 && $total_height <=8 && $max_width < 19) {
$extra_weight = $Medium_envelope;
}
if( $total_height > 8 && $total_height <=16 && $max_width < 19) {
$extra_weight = $Large_envelope;
}
if( $total_height > 16 && $total_height <=22) {
$extra_weight = $Small_box;
}
if( $total_height > 22 && $total_height <=38) {
$extra_weight = $Medium_box;
}
//
将 $extra_weight(盒子重量)除以购物车商品数量。然后再次循环浏览购物车商品,将划分后的重量添加到每个商品中。
$xtr_weight_per_item = $extra_weight / $cart_items_qty;
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_weight( $cart_item['data']->get_weight()+$xtr_weight_per_item);
}
}
//
结账时显示计算重量以进行测试
add_action( 'woocommerce_cart_totals_after_order_total', 'display_wc_cart_total_weight_after_order_total' );
function display_wc_cart_total_weight_after_order_total() {
?>
<tr class="order-total">
<th><?php esc_html_e( 'Total weight', 'woocommerce' ); ?></th>
<td data-title="<?php esc_attr_e( 'Total weight', 'woocommerce' ); ?>"><?php echo wc_format_weight( WC()->cart->get_cart_contents_weight() ); ?></td>
</tr>
<?php
}