首页 > 解决方案 > WooCommerce:从免费送货的阈值计数中排除产品

问题描述

我已经为英国的某人设置了 3 件商品的门槛以获得免费送货服务。每次有人添加特定类别的产品时,我都会自动将产品添加到他们的购物车中,这是免费礼物。

我的问题是,我试图从阈值计数中排除此免费礼物,因为目前正在计算此免费礼物,并且人们在购物车中没有 3 个实际收费物品的情况下获得免费送货。

我不确定如何将产品 id 29 从计数中排除,因此将不胜感激。

add_action( 'woocommerce_before_cart', 'ds_free_shipping_cart_notice' );
  
function ds_free_shipping_cart_notice() {
    $threshold = 3;
    $current = WC()->cart->get_cart_contents_count();
    $billing_country = WC()->customer->get_billing_country();
    if ( $current < $threshold && WC()->customer->get_billing_country() == 'GB' ) {
        wc_print_notice( 'Nearly there! Order ' . ( $threshold - $current ) . ' more and shipping is on us', 'notice' );
    }
    
}

标签: phpwoocommerce

解决方案


我没有设置 woocommerce 来对此进行测试,但这是您需要的逻辑类型:

$cart_items = WC()->cart->get_cart();
$current = WC()->cart->get_cart_contents_count();
foreach($cart_items as $item => $values) { 
  if ($values['product_id'] == 29) {
   --$current;
  }
} 

这个答案也应该有所帮助。

但总的来说,这是一种非常脆弱的方法,因为每次提供新礼物时都需要更改硬编码的产品 ID。最好为您的产品添加一个名为“免费礼物”或类似名称的自定义字段,根据需要为作为免费礼物提供的物品设置该值,然后设置代码以从免费送货中排除任何这些物品.


推荐阅读