本文介紹了根據 Woocommerce 中的總重量添加自定義費用的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
在 WooCommerce 中,我嘗試根據購物車重量添加額外的運費.
In WooCommerce, I am trying to add a an additional shipping fee based on cart weight.
- 第一個
1500g
的費用是 50 美元. - 在
1500g
之上,我們以 1000g 為單位在最初的 50 美元基礎上加 10 美元
- For the first
1500g
the fee is 50$. - Above
1500g
we add 10$ to this initial $50 by steps of 1000g
例如:
- 如果購物車重量為 700 克,我們將收取 50 美元的費用,
- 如果購物車重量為 2600 克,我們將收取 70 美元(50 美元 + 10 美元 + 10 美元)的費用……
我被困在計算上:
function weight_add_cart_fee() {
$feeaddtocart = get_option('feeaddtocart');
$customweight = get_option('customweight');
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_weight = WC()->cart->get_cart_contents_weight();
if ($cart_weight <= 500 ) {
$get_cart_total = $woocommerce->cart->get_cart_total();
$newtotal = $get_cart_total + 50;
WC()->cart->add_fee( __('Extra charge (weight): ', 'your_theme_slug'), $newtotal, false );
}
}
我怎樣才能做到這一點?任何幫助表示贊賞.
How can I achieve this? Any help is appreciated.
推薦答案
使用 woocommerce_cart_calculate_fees
動作鉤子中掛鉤的自定義函數可以非常輕松地完成...
It can be done very easily with a custom function hooked in woocommerce_cart_calculate_fees
action hook…
更新:
- 添加了以克為單位的購物車重量轉換(而不是默認公斤)
- 現在前 1500 克的費用是 50 美元(而不是 500 克)
- 現在超過 1500 克,它會以 1000 克為單位增加 10 美元.
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 30, 1 );
function shipping_weight_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Convert cart weight in grams
$cart_weight = $cart->get_cart_contents_weight() * 1000;
$fee = 50; // Starting Fee below 500g
// Above 500g we add $10 to the initial fee by steps of 1000g
if( $cart_weight > 1500 ){
for( $i = 1500; $i < $cart_weight; $i += 1000 ){
$fee += 10;
}
}
// Setting the calculated fee based on weight
$cart->add_fee( __( 'Weight shipping fee' ), $fee, false );
}
代碼位于活動子主題(或活動主題)的 function.php 文件中.
經過測試并有效.
這篇關于根據 Woocommerce 中的總重量添加自定義費用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!