Php woocommerce-获取购物车总数作为编号

Php woocommerce-获取购物车总数作为编号,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我想在我的woocommerce插件中获得购物车的总价 我想得到一个浮点数,比如:21.00,但我不知道如何得到它。我的代码输出奇怪的结果,这是我的确切代码: $total = $woocommerce->cart->get_total(); $total_a = WC()->cart->get_total(); $total1 = $woocommerce->cart->get_total_ex_tax(); $to

我想在我的woocommerce插件中获得购物车的总价

我想得到一个浮点数,比如:21.00,但我不知道如何得到它。我的代码输出奇怪的结果,这是我的确切代码:

$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();
产出:

0,00 €
0,00 €
0,00 €
0,00 €
21,00 €
21,00 €
如果我把字符串转换成float,结果当然是0.00


如何以浮点数的形式获取购物车总数,有什么帮助吗

直接访问
total
属性即可,它是公共的:

global $woocommerce;
echo $woocommerce->cart->total;

您还可以根据需要将$amount转换为浮点值。

我有这样的代码,工作非常完美:

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

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

WC()->cart->cart\u内容总量在2020年与Woocommerce 4+

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

有一些方法,您不需要从属性获取它们

使用:
WC()->cart->get\u cart\u contents\u total()

而不是:
WC()->cart->cart\u contents\u total


并使用:
WC()->cart->get\u taxes\u total()


而不是:
WC()->cart->tax\u total
Woocommerce 4.8
WC()->cart->total
工作正常,虽然在没有getter帮助的情况下获取此值让我有点担心,但这似乎是目前最简单的方法。

最好的方法是使用
get\u total()
在非默认“视图”的上下文中传递时。当上下文为“查看”时,将格式化价格以供显示。当设置为其他值时,它将传回原始值

例如:

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


还值得注意的是,
$woocommerce
(当然前提是您已经访问了全球第一个)与
WC()
完全相同。我建议尽可能选择
WC()

查看购物车类。方法使用
wc\u price()
格式化价格。所以,正如@José所指出的,您只需要访问公共属性。它似乎不适用于woocommerce 2.6.x版或更高版本。你有其他的方法吗?请描述你的答案。这种方法不包括运费。不是反过来吗?当价格含税时,不应加税。谢谢,终于有了2020年的工作。。。我不敢相信在WooCommerce中几乎不可能以float/int的形式获取购物车总金额。奇怪的是,这是真的,尽管:
WC()->cart->total
仍然适用于我,但是在没有getter的情况下获取这个值让我有点担心。
WC()->cart->get_total( 'raw' );