In woocommerce, I have added a custom fee using the following code:
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1 );
function custom_fee_based_on_cart_total( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// The percetage
$percent = 10; // 15%
// The cart total
$cart_total = $cart_object->cart_contents_total;
// The conditional Calculation
$fee = $cart_total >= 25 ? $cart_total * $percent / 100 : 0;
if ( $fee != 0 )
$cart_object->add_fee( __( "Gratuity", "woocommerce" ), $fee, false );
}
I just want to swipe the fees order like I want "Fee per person" after the sub total and "Gratuity" after "Fee per person".
the WooCommerce class WC_Cart_Fees is sorting by default the fees by amount.
reference WC_Cart_Fees
and in order to modify the default behavior of WooCommerce you need to override cart-totals.php
which you can find under under woocommerce plugin dir woocommerce/templates/cart/cart-totals.php
create dir under your child theme name woocommerce/cart and the copy that file to this dir
go to line 61 which you can find the following code :
<?php foreach ( WC()->cart->get_fees() as $fee ) : ?>
<tr class="fee">
<th><?php echo esc_html( $fee->name ); ?></th>
<td data-title="<?php echo esc_attr( $fee->name ); ?>"><?php wc_cart_totals_fee_html( $fee ); ?></td>
</tr>
<?php endforeach; ?>
change that code to the following :
<?php
$array = json_decode(json_encode(WC()->cart->get_fees()), true);
ksort($array); //
foreach ($array as $fee): ?>
<tr class="fee">
<th><?php echo esc_html($fee['name']); ?></th>
<td data-title="<?php echo esc_attr($fee['name']); ?>"><?php echo
$fee['total']; ?></td>
</tr>
<?php endforeach;?>
code explanation :
basicly what we have done here is geting all fees from the WC class and convert it to array using php built in function json_encode() in order to be able to sort the array in anyway we need, i used ksort() function to sort the array based on the key in ascending order, and then print back the fees:
here is screenshot of the output :