简体   繁体   中英

woocommerce - Get Cart Total as number

I want to get total price of cart in my woocommerce plugin.

I want to get it as a float number like so: 21.00 but I don't know how to get it. My code outputs weird results, this is my exact code:

$total         = $woocommerce->cart->get_total();
$total_a       = WC()->cart->get_total();
$total1        = $woocommerce->cart->get_total_ex_tax();
$total1_a      = WC()->cart->get_total_ex_tax();
$total2        = $woocommerce->cart->get_cart_total();
$total2_a      = WC()->cart->get_cart_total();

outputs:

0,00 €
0,00 €
0,00 €
0,00 €
21,00 €
21,00 €

and if I convert from string to float the result is of course 0.00.

Any help how to get cart total in the form of float number ?

I have code like this and working perfect:

if ( ! WC()->cart->prices_include_tax ) {
    $amount = WC()->cart->cart_contents_total;
} else {
    $amount = WC()->cart->cart_contents_total + WC()->cart->tax_total;
}

good luck !

Just access the total property directly, it's public:

global $woocommerce;
echo $woocommerce->cart->total;
global $woocommerce;
$amount = $woocommerce->cart->cart_contents_total+$woocommerce->cart->tax_total;

You can also convert $amount in float value as per your requirement.

global $woocommerce;
$woocommerce->cart->cart_contents_total (Cart total)
$woocommerce->cart->tax_total (tax total)
$woocommerce->cart->shipping_total (shipping total)

试试这个 WC()->cart->cart_contents_total

In 2020 with Woocommerce 4+

$total_cart = WC()->cart->get_displayed_subtotal(); // without taxs and shipping fees
echo $total_cart; // ex: 0.00

The best approach is to use get_total() while passing in a context other than the default of 'view'. When the context is view, the price will be formatted for display. When set to anything else, it'll pass back the raw value.

Example:

WC()->cart->get_total( 'raw' );

It's also worth noting that $woocommerce (providing you've accessed the global first of course) is exactly the same as WC() . I'd recommend preferring WC() whereever possible.

There are methods for it, you don't need to get them from a property.

Use: WC()->cart->get_cart_contents_total()

Instead of: WC()->cart->cart_contents_total


And use: WC()->cart->get_taxes_total()

Instead of: WC()->cart->tax_total

Woocommerce 4.8 WC()->cart->total工作正常,虽然我有点担心在没有 getter 帮助的情况下获得这个值,但它现在似乎是最简单的方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM