2017-09-06 9 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を使用する必要があります。

また、カートオブジェクトはすでにこのフックに含まれているため、フックされた関数の引数として追加することができます。
また、このフックを使用する必要はありません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

関連する問題