Joakim Carlsten
Joakim Carlsten

Reputation: 93

WooCommerce calculate totals

I'm trying to display total cart value (including VAT) in the header of my site. However - if I try to use cart->get_cart_total() I get the price excluding VAT. If I try to use cart->get_totals() I get a value of 0 until I visit the cart page - then it shows the correct value (even if I surf to other pages).

Ok, so I tried to run cart->calculate_totals() before fetching the cart->get_totals() but it seems to reset the value... It still works fine on the cart page though.

Could someone please help me here? Thanks

Upvotes: 4

Views: 10459

Answers (2)

Johan Palmfjord
Johan Palmfjord

Reputation: 681

I struggled with this a bit myself, but I found a solution. WooCommerce only calculates grand totals and shipping when on cart or checkout page. I guess this has something to do with performance. You can see this in includes/class-wc-cart.php on line 1290 and 1318.

My solution was adding this snippet to functions.php. I don't know if it can be considered hacky, but it solved the problem :)

<?php
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
    define( 'WOOCOMMERCE_CART', true );
}
WC()->cart->calculate_totals();

Upvotes: 2

Joakim Carlsten
Joakim Carlsten

Reputation: 93

I managed to get the desired result by using cart->get_cart_subtotal().

Now I just want to remove the "(incl. tax)" that gets amended to the result.

Upvotes: 2

Related Questions