Search code examples
phpwordpresswoocommercecartfee

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

Solution

  • Your code contains some mistakes

    • No need to use WC()->cart, $cart is passed to the function
    • $quantiy is overwritten on each loop
    • Same for adding the fee, this is overwritten on each loop

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