[英]Add fee for certain products in WooCommerce cart
I have a working script that adds a fee for certain products in an array.我有一个工作脚本,可以为数组中的某些产品添加费用。 But it only adds the fee for the first product in the array.但它只增加了数组中第一个产品的费用。
I have tried different options with my knowledge but it doesn't work.据我所知,我尝试了不同的选择,但没有用。 Any advice on what i'm doing wrong?关于我做错了什么的任何建议?
This is the code:这是代码:
/* 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 );
}
Your code contains some mistakes您的代码包含一些错误
WC()->cart
, $cart
is passed to the function无需使用WC()->cart
, $cart
被传递给 function$quantiy
is overwritten on each loop $quantiy
在每个循环中被覆盖So you get:所以你得到:
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.