[英]Add fee for certain products in WooCommerce cart
我有一個工作腳本,可以為數組中的某些產品添加費用。 但它只增加了數組中第一個產品的費用。
據我所知,我嘗試了不同的選擇,但沒有用。 關於我做錯了什么的任何建議?
這是代碼:
/* Add fee to specific product*/
add_action('woocommerce_cart_calculate_fees', 'statie_geld');
function statie_geld() {
if (is_admin() && !defined('DOING_AJAX')) {return;}
foreach( WC()->cart->get_cart() as $item_keys => $item ) {
$quantiy = $item['quantity']; //get quantity from cart
if( in_array( $item['product_id'], statiegeld_ids() )) {
WC()->cart->add_fee(__('Statiegeld Petfles 24'), 3.60 * $quantiy );
}
}
}
function statiegeld_ids() {
return array( 4535, 4537, 89694, 89706, 3223, 4742, 14846, 26972, 32925, 32927, 32929, 37475 );
}
您的代碼包含一些錯誤
WC()->cart
, $cart
被傳遞給 function$quantiy
在每個循環中被覆蓋所以你得到:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Initialize
$quantity = 0;
// Loop though each cart item
foreach ( $cart->get_cart() as $cart_item ) {
// Compare
if ( in_array( $cart_item['product_id'], statiegeld_ids() ) ) {
// Addition
// Get product quantity in cart
$quantity += $cart_item['quantity'];
}
}
// Greater than
if ( $quantity > 0 ) {
// Add fee
$cart->add_fee( __( 'Statiegeld Petfles 24', 'woocommerce' ), 3.60 * $quantity );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
// Specify the product IDs
function statiegeld_ids() {
return array( 4535, 4537, 89694, 89706, 3223, 4742, 14846, 26972, 32925, 32927, 32929, 37475 );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.