I want to get cart contents total in woocommerce within woocommerce_before_calculate_totals
hook. So to achieve this I am using this code
add_action( 'woocommerce_before_calculate_totals', 'get_before_calculate_totals', 10 );
function get_before_calculate_totals( $cart_object ) {
global $woocommerce;
echo WC()->cart->get_cart_contents_total(); //returns 0
}
But it returns 0 every time. So can someone tell me how to get cart total without currency within woocommerce_before_calculate_totals
hook?
Any help and suggestion would be really appreciable.
As woocommerce_before_calculate_totals
is used before any totals calculations, use instead the following that makes items subtotals calculations:
add_action( 'woocommerce_before_calculate_totals', 'get_subtotal_before_calculate_totals', 10 );
function get_subtotal_before_calculate_totals( $cart ) {
$subtotal_excl_tax = $subtotal_incl_tax = 0; // Initializing
// Loop though cart items
foreach( $cart->get_cart() as $cart_item ) {
$subtotal_excl_tax += $cart_item['line_subtotal'];
$subtotal_incl_tax += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax'];
}
echo '<p>Subtotal excl. tax: ' . $subtotal_excl_tax . '</p>'; // Testing output
echo '<p>Subtotal Incl. tax: ' . $subtotal_incl_tax . '</p>'; // Testing output
}