I need to add Handling fee in checkout page for some state. For this I am using woocommerce add_fee option. But my problem is on checkout page the handling fee is showing but not add to subtotal. Here is my code

add_action( 'woocommerce_cart_calculate_fees','xa_custom_surcharge' );
function xa_custom_surcharge() {
    global $woocommerce;
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $state= array('MH');
    $surcharge  = 10;

    if ( in_array( WC()->customer->shipping_state, $state ) ) {
        $woocommerce->cart->add_fee( 'Additional Charge', $surcharge, true, '' );
    }
}

Can anyone please help me.

1 Answers

0
LoicTheAztec On

Your code is outdated since WooCommerce 3:

  • Properties can't not be accessed anymore on CRUD objects, so you should use instead methods like get_shipping_state() in your case.
  • global $woocommerce and $woocommerce->cart are outdated & replaced directly by WC()->cart
  • The WC_Cart Object $cart variable is available in the hooked function as an argument.

The correct code is:

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

    $state = array('MH');
    $surcharge  = 10;

    if ( in_array( WC()->customer->get_shipping_state(), $state ) ) {
        $cart->add_fee( 'Additional Charge', $surcharge, true );
    }
}

Now when using the Fee API, the fee amount is displayed as a total and added to gran total at the end, but NOT to the subtotal:

enter image description here

The subtotal in WooCommerce is made only from cart items subtotals…