在wooccommerce上创建免费商品的运输方法



我希望根据购物车中的物品创建两个单独的运输集。我想要"运费舱"的免费运费;假日套餐";以及产品类别"免费送货";咖啡";当推车中有两袋以上的咖啡时。然后我想把剩下的物品放进不同的运输";容器";。

目前,当里面有两种不同的咖啡时,我可以让所有的咖啡都发挥作用(因此咖啡计数增加了(,但当一种咖啡中有两种时,它不会将其分开。

/* Puts items with "holiday-package" shipping class into a different shipping package. */
function hdm_woocommerce_cart_shipping_packages( $packages ) {
// Reset the packages
$packages = array();
// Free items
$freeshipping_items = array();
$regular_items      = array();
$coffee_count = 0;
//get product category and count up each item in that category
foreach ( WC()->cart->get_cart() as $item ) {
$quantity = $item['quantity'];
if ($item['data']->get_shipping_class() == 'coffee') {
$coffee_count++; }
elseif ($quantity >= 2 && $item['data']->get_shipping_class() == 'coffee') {
$coffee_count = 2;
}
}
// Sort free from regular.
foreach( WC()->cart->get_cart() as $item ) {
if( $item['data']->needs_shipping() ) {
if( $item['data']->get_shipping_class() == 'holiday-packages' ) {
$freeshipping_items[] = $item;
}
elseif ($item['data']->get_shipping_class() == 'coffee' && $coffee_count >= 2){
$freeshipping_items[] = $item;
}
else {
$regular_items[] = $item;
}
}
}
// Put inside packages:
if( $regular_items ) {
$packages[] = array(
'ship_via'        => array(),
'contents'        => $regular_items,
'contents_cost'   => array_sum(wp_list_pluck($regular_items, 'line_total')),
'applied_coupons' => WC()->cart->applied_coupons,
'destination'     => array(
'country'   => WC()->customer->get_shipping_country(),
'state'     => WC()->customer->get_shipping_state(),
'postcode'  => WC()->customer->get_shipping_postcode(),
'city'      => WC()->customer->get_shipping_city(),
'address'   => WC()->customer->get_shipping_address(),
'address_2' => WC()->customer->get_shipping_address_2()
)
);
}
if( $freeshipping_items ) {
$packages[] = array(
'ship_via'        => array( 'flat_rate' ),
'contents'        => $freeshipping_items,
'contents_cost'   => array_sum(wp_list_pluck($freeshipping_items, 'line_total')),
'applied_coupons' => WC()->cart->applied_coupons,
'destination'     => array(
'country'   => WC()->customer->get_shipping_country(),
'state'     => WC()->customer->get_shipping_state(),
'postcode'  => WC()->customer->get_shipping_postcode(),
'city'      => WC()->customer->get_shipping_city(),
'address'   => WC()->customer->get_shipping_address(),
'address_2' => WC()->customer->get_shipping_address_2()
)
);
}
return $packages;
}
add_filter('woocommerce_cart_shipping_packages', 'hdm_woocommerce_cart_shipping_packages');

UPDATE:我正要通过更改来修复它

elseif ($quantity >= 2 && $item['data']->get_shipping_class() == 'coffee') {
$coffee_count = 2;
}

if ($quantity >= 2 && $item['data']->get_shipping_class() == 'coffee') {
$coffee_count = 2;
}

我不认为它能提供正确的数量,但它能满足我的需求。如果有人对如何更好地写这篇文章有任何建议,我们将不胜感激。

最新更新