2017-09-06 210 views
1

我想根據藝術總額中的特定金額添加費用。我想顯示購物車總數是否等於或大於總「$$$」金額添加費用,否則不要添加。根據WooCommerce中的特定購物車總額添加費用

我知道這項工作將其添加到總計,但我不認爲它是檢查,看它是否低於美元金額。

function woo_add_custom_fees(){ 

    $cart_total = 0; 

    // Set here your percentage 
    $percentage = 0.15; 

    foreach(WC()->cart->get_cart() as $item){ 
     $cart_total += $item["line_total"]; 
    } 
    $fee = $cart_total * $percentage; 

    if ( WC()->cart->total >= 25) { 

    WC()->cart->add_fee("Gratuity", $fee, false, ''); 

    } 

    else { 

     return WC()->cart->total; 
    } 
} 
add_action('woocommerce_cart_calculate_fees' , 'woo_add_custom_fees'); 
add_action('woocommerce_after_cart_item_quantity_update', 'woo_add_custom_fees'); 

我在做什麼錯了?

+0

'else'部分是「下」 – Reigel

回答

1

woocommerce_cart_calculate_fees行動掛鉤,WC()->cart->total總是返回0,因爲這鉤子的車總金額計算之前解僱......

你應該更好地利用WC()->cart->cart_contents_total代替。

另外cart對象已經包含在這個鉤子中,所以你可以把它作爲一個參數添加到你的鉤子函數中。
你也不需要使用這個鉤子woocommerce_after_cart_item_quantity_update

這是你重新編號:

add_action('woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1); 
function custom_fee_based_on_cart_total($cart_object) { 

    if (is_admin() && ! defined('DOING_AJAX')) return; 

    // The percetage 
    $percent = 15; // 15% 
    // The cart total 
    $cart_total = $cart_object->cart_contents_total; 

    // The conditional Calculation 
    $fee = $cart_total >= 25 ? $cart_total * $percent/100 : 0; 

    if ($fee != 0) 
     $cart_object->add_fee(__("Gratuity", "woocommerce"), $fee, false); 
} 

代碼放在您的活動子主題(或主題)的function.php文件或也以任何插件文件。

此代碼已經過測試並可正常工作。

+0

謝謝!這絕對有幫助 – nholloway4

相關問題