Exclude some products from calculated additional fee in WooCommerce

153 views Asked by At

I wrote This function to add a 9% extra fee on a gateway just on the checkout page.

Now, I want to exclude some products by ID from increasing additional fees in a function.

How can I simply do this with minimal changes in the code?

add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway' );
function add_checkout_fee_for_gateway() {
    // Check if we are on the checkout page
    if ( is_checkout() ) {
        global $woocommerce;
        $chosen_gateway = $woocommerce->session->chosen_payment_method;
        if ( $chosen_gateway == 'paypal' ) {
            $percentage = 0.09;
            
            /* for all products prices + shipping (total price)
            $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
            */
            
            $surcharge = ( $woocommerce->cart->get_subtotal() ) * $percentage;
            $woocommerce->cart->add_fee( '9% value added tax', $surcharge, true, '' );
        }
    }
}
1

There are 1 answers

0
LoicTheAztec On BEST ANSWER

The code that you are using is a bit outdated since WooCommerce 3.

The following code will add a percentage fee from specific cart items calculated subtotal (excluding some defined products):

add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway', 10, 1 );
function add_checkout_fee_for_gateway( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    // Only on checkout page and for specific payment method ID
    if ( is_checkout() && ! is_wc_endpoint_url() 
    && WC()->session->get('chosen_payment_method') === 'paypal' ) {
        // Here below define the product IDs to be excluded
        $excluded_product_ids = array(15, 18);
        $percentage_rate      = 0.09; // Defined percentage rate
        $custom_subtotal      = 0; // Initializing
        
        // Loop through cart items
        foreach( $cart->get_cart() as $item ) {
            // Calculate items subtotal from non excluded products
            if( ! in_array($item['product_id'], $excluded_product_ids) ) {
                $custom_subtotal += (float) $item['line_subtotal'];
            }
        }

        if ( $custom_subtotal > 0 ) {
            $cart->add_fee( __('9% value added tax'), ($custom_subtotal * $percentage_rate), true, '' );
        }
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.