Giovanni Giovanni - 3 years ago 195
PHP Question

Additional fees based on product type in Woocommerce

What I am trying to do is to add and display, to the checkout page, a new fee if the product type is an "auction". The problem I have with my code is that the new fee is displayed but not added to the total cost.

I've used this code
Change Cart total price in WooCommerce
and customized it with this function:

add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );
function action_cart_calculate_totals( $cart_object ) {
if ( (is_admin() && ! defined( 'DOING_AJAX')) || WC()->cart->is_empty() )
return;
foreach ( WC()->cart->cart_contents as $key => $values ) {
if ( $values['data']->get_type() == 'auction' ) {
$buyerfee = 0.10; // auction buyer fee
$surcharge = $cart_object->cart_contents_total * $buyerfee;
$cart_object->add_fee( 'Auction Fee (10%)', $surcharge, true, '' );
}
}
}

Answer Source

In this case, you need to use woocommerce_cart_calculate_fees action hook instead:

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

    $is_auction = false;
    foreach ( $cart_object->cart_contents as $item ) {
        if ( $item['data']->is_type( 'auction' ) ) {
            $is_auction = true;
            break;
        }
    }
    if( $is_auction ){
        $percent  = 10; // auction buyer fee (in percetage)
        $fee = $cart_object->cart_contents_total * $percent / 100;
        $cart_object->add_fee( "Auction Fee ($percent%)", $fee, true );
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Code is tested and works

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download