Programmatically add a custom fee to the WooCommerce cart

Charging additional fees to an e-com order is a common ask from many online retailers using WooCommerce. This post gets right to the point with a couple solid code snippets to get your custom fee working right away.

A PHP task dropped into my lap recently that required adding a setup fee for each item in a WooCommerce cart that matched a certain criteria. Opening up the WooCommerce documentation revealed an action hook designed specifically for allowing 3rd-party fee calculations to be processed and added to the order.

The logic below looks for a setup fee within the meta data of each product. If it doesn’t exist, it gets skipped. You can replace this code with setup fee conditional logic specific to your project.

public function maybe_add_setup_fee() {

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

    $count = 0;
    $setup_fee = 0.00;

    foreach ( WC()->cart->get_cart() as $cart_item ) {

        // Determine product ID
        $id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];


        // Retrieve custom setup fee meta data
        $fee = get_post_meta( $id, '_setup_fee', true );

        if ( empty( $fee ) )
            continue;

        $count += $cart_item['quantity'];
        $setup_fee += ( $cart_item['quantity'] * floatval( $fee ) );
    }

    if ( $setup_fee > 0 )
        WC()->cart->add_fee("Setup Fee (x$count)", $setup_fee, false, '');

}

Now just implement the WooCommerce cart fee calculation hook by adding this snippet to your functions.php or relevant class file:

add_action( 'woocommerce_cart_calculate_fees', 'maybe_add_setup_fee' );

Happy programming 😜.