根据Woocommerce中的其他购物车数量自动将特定产品添加到购物车

时间:2019-01-24 06:11:42

标签: php wordpress woocommerce product cart

我正在尝试根据购物车中有多少商品向购物车中添加一个名为(送货费)的产品。

购物车示例:
产品A(数量5)
产品B(数量2)
产品C(数量4)
送货费用(数量3)**之所以为3,是因为这是应该在添加送货费用产品之前添加到购物车中的总订单项。

我的代码有麻烦:

/* Function to get total Products (line items) not qty of each */
function count_item_in_cart() {
    global $woocommerce; 
    $counter = 0; 

    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
        $counter++;
    }
    return $counter;
}

/* Add DC (Delivery Charge Product) to Cart based on qty */ 
add_action( 'template_redirect', 'delivery_charge_add_product_to_cart' ); 
function delivery_charge_add_product_to_cart() {
    /* Establish Product Delivery Charge Product ID */
    global $woocommerce;
    $product_id = 4490;  /* Product ID to add to cart */
    $quantity = count_item_in_cart(); 

    if ($quantity > 0) {
        WC()->cart->add_to_cart( $product_id, $quantity); 
    }
}

它总是返回一个更大的数字。我认为它是在计算每种产品的数量而不是实际产品的数量。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

以下代码将在每次将商品添加到购物车时自动向购物车添加/更新您的附加产品“送货费用”,并将处理所有可能的情况:

{{ form.field_name.label }}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。

相关问题