問題描述
基于"woocommerce 在結帳和購物車中更改價格頁面" 回答更改結帳頁面總價的代碼,我添加了一些額外的代碼來計算用戶在購物車中擁有的產品,如果用戶在購物車中有 9 個產品,則添加一些價格總計:
Based on "woocommerce change price in checkout and cart page" answer code that change the total price in checkout page, I have added some extra code to count the products that user have in cart and if user had like 9 products in cart then add some price to total:
add_action( 'woocommerce_before_cart_totals', 'custom_cart_total' , 'get_cart_contents_count');
function custom_cart_total() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if (WC()->cart->get_cart_contents_count() == 9){
WC()->cart->total += 15;
}
elseif(WC()->cart->get_cart_contents_count() == 6){
WC()->cart->total += 14;
}
elseif(WC()->cart->get_cart_contents_count() == 4){
WC()->cart->total += 13;
}
}
但它不起作用.這張圖片將說明一切:
如果有人可以更正代碼并告訴我如何顯示圖片中的消息,我將不勝感激
I will appreciate if anyone could correct the code and tell me how can I display the message like in the picture
推薦答案
你最好改用 FEE API,這樣:
You should better use the FEE API instead, this way:
// Add a custom packing fee based on item count
add_action( 'woocommerce_cart_calculate_fees', 'custom_packing_fee', 10, 1 );
function custom_packing_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
return;
$count = $cart->get_cart_contents_count();
if ( $count >= 9 ){
$fee = 15;
}
elseif( $count >= 6 && $count < 9 ){
$fee = 14;
}
elseif( $count >= 4 && $count < 6 ){
$fee = 13;
}
if ( isset($fee) && $fee > 0 ) {
$label = sprintf( __('Box fee (%d items)'), $count);
$cart->add_fee( $label, $fee, false );
}
}
代碼位于您的活動子主題(或活動主題)的functions.php 文件中.經測試有效.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
如果您想為包裝費啟用稅金,請將第三個參數從 false
更改為 true
.
If you want to enable taxes for the packing fee, change the third argument from
false
totrue
.
這篇關于基于 WooCommerce 中購物車項目數量的附加價格的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!