【问题标题】:Add fee for certain products in WooCommerce cart在 WooCommerce 购物车中为某些产品添加费用
【发布时间】:2021-10-26 16:46:32
【问题描述】:

我有一个工作脚本,它为数组中的某些产品添加费用。 但它只增加了数组中第一个产品的费用。

我根据我的知识尝试了不同的选项,但它不起作用。关于我做错了什么有什么建议吗?

这是代码:

/* 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 ); 
} 

【问题讨论】:

  • 在循环的第一次迭代过程中是否检查过日志是否有任何错误?也许只有第一个产品 ID 在您的 statiegeld_ids 中?

标签: php wordpress woocommerce cart fee


【解决方案1】:

您的代码包含一些错误

  • 不用WC()->cart$cart传递给函数
  • $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 ); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2015-05-03
    • 1970-01-01
    • 2020-10-15
    • 2014-11-21
    • 1970-01-01
    • 2021-05-09
    • 2021-08-22
    相关资源
    最近更新 更多