在 WooCommerce 中,我使用代码在将任何菜品添加到购物车时自动添加包装。
功能如下:
菜品在购物车中,添加了1个饭盒
菜品在购物车中,增加了2个饭盒
菜在购物车里,增加了3个饭盒
有 3 个饭盒,所以现在添加 1 个包裹
function add_delivery_charge_to_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$lunchbox_id = 5737; // "LunchBox" to be added to cart
$pakket_id = 5738; // "Pakket" to be added to cart
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Check if "LunchBox" product is already in cart
if( $cart_item['data']->get_id() == $lunchbox_id ) {
$lunchbox_key = $cart_item_key;
$lunchbox_qty = $cart_item['quantity'];
}
// Check if "Pakket" product is already in cart
if( $cart_item['data']->get_id() == $pakket_id ) {
$pakket_key = $cart_item_key;
$pakket_qty = $cart_item['quantity'];
}
}
// Get total items in cart, counts number of products and quantity per product
$total_items_in_cart = WC()->cart->get_cart_contents_count();
// If product "LunchBox" is in cart, we check the quantity to update it if needed
if ( isset($lunchbox_key) && $lunchbox_qty != $total_items_in_cart ) {
// Lunchbox total = total_items_in_cart
$lunchbox_total = $total_items_in_cart;
// Isset lunchbox qty, lunchbox total - lunchbox qty
if ( isset($lunchbox_qty) ) {
$lunchbox_total = $lunchbox_total - $lunchbox_qty;
}
// Isset pakket qty, lunchbox total - pakket qty
if ( isset($pakket_qty) ) {
$lunchbox_total = $lunchbox_total - $pakket_qty;
}
有一个小问题。购物车中所有自动添加的包装都与其他产品混合分类。
如何使购物车中的包装始终位于产品列表的底部?
哔哔one