2

Trying to add a commission fee to the WooCommerce checkout based on 5% multiplied by subtotal. But, all I get is a blank page and the site stops working.

This is the code:

add_action( 'woocommerce_cart_calculate_fees', 'add_commission', 10, 1 ); 
function add_commission( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // global, is this needed?
    global $woocommerce;

    // get the cart subtotal
    $subtotal = WC()->cart->get_cart_subtotal();

    // commission fee of 5%
    $commission_fee = 0.05;
    
    // the total commission is the 5% multiplied by the subtotal
    $total_commission = $commission_fee * $subtotal;

    // apply the commission
    $cart->add_fee( 'Commission', $total_commission, true );
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

3

The main error is in get_cart_subtotal() method, which is the formatted cart subtotal HTML (a string) that you are trying to multiply with a float number.

Instead, you should use get_subtotal() method (non formatted subtotal without taxes amount).

So the correct code is:

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

    // get the cart subtotal
    $subtotal = $cart->get_subtotal();

    // commission fee of 5%
    $commission_fee = 0.05;
    
    // the total commission is the 5% multiplied by the subtotal
    $total_commission = $commission_fee * $subtotal;

    // apply the commission
    $cart->add_fee( 'Commission', $total_commission, true );
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399