![](/img/trans.png)
[英]Add an extra cost to product price based on cart item count in Woocommerce
[英]Additional price based on cart item count in WooCommerce
基於“ 結帳和購物車頁面中的 woocommerce 更改價格” 更改結帳頁面中總價的答案代碼,我添加了一些額外的代碼來計算用戶在購物車中擁有的產品,如果用戶在購物車中有 9 個產品,則添加一些總價:
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;
}
}
但它不起作用。 這張圖片將解釋一切:
如果有人可以更正代碼並告訴我如何顯示圖片中的消息,我將不勝感激
你應該更好地使用 FEE API,這樣:
// 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 文件中。 測試和工作。
如果要為包裝費啟用稅,請將第三個參數從
false
更改為true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.