在 WooCommerce 3+ 中获取购物车总数作为浮点数
Get cart total as a float number in WooCommerce 3+
在 WooCommerce 中,
<?php echo WC()->cart->get_cart_total(); ?>
给我 1,750.00 欧元
我怎样才能把它作为一个浮点数来乘以它?
我尝试了这两个 SO 问题中的所有解决方案:
Unable to get cart total in woocommerce
woocommerce - Get Cart Total as number
全部过时且无法正常工作。有人知道怎么做吗?
可以参考WooCommerce WC_Cart
official documentation
这应该有效:
WC()->cart->get_total("anything_else_than_'view'");
说明:
感谢 btomw that pointed out that an argument need to be defined in WC_Cart
get_total()
method. If you call this method without defining an argument (that should be anything else than 'view' string), the output is going to be the formatted total price, as 'view'
default argument will be used by this method. So if you want to get a float value (non formatted)
, set as argument anything else that is not 'view', even an empty string like ''
. As you can see on this method documentation,它是为了向后兼容 WooCommerce 3.2。
作为 Sar Putnik 答案的替代方案,使用 WC_Cart
对象,您 可以像 total
一样直接访问属性 ,这给出了非格式化数字:
$total = WC()->cart->total;
// Testing output
var_dump($total);
如果使用 $total = WC()->cart->get_total("");
将给出相同的输出
Note that, since WooCommerce 3, on other WooCommerce instance objects you can't access properties directly… But some few classes as WC_Cart
still allow that.
在 WooCommerce 中,
<?php echo WC()->cart->get_cart_total(); ?>
给我 1,750.00 欧元
我怎样才能把它作为一个浮点数来乘以它?
我尝试了这两个 SO 问题中的所有解决方案:
Unable to get cart total in woocommerce
woocommerce - Get Cart Total as number
全部过时且无法正常工作。有人知道怎么做吗?
可以参考WooCommerce WC_Cart
official documentation
这应该有效:
WC()->cart->get_total("anything_else_than_'view'");
说明:
感谢 btomw that pointed out that an argument need to be defined in WC_Cart
get_total()
method. If you call this method without defining an argument (that should be anything else than 'view' string), the output is going to be the formatted total price, as 'view'
default argument will be used by this method. So if you want to get a float value (non formatted)
, set as argument anything else that is not 'view', even an empty string like ''
. As you can see on this method documentation,它是为了向后兼容 WooCommerce 3.2。
作为 Sar Putnik 答案的替代方案,使用 WC_Cart
对象,您 可以像 total
一样直接访问属性 ,这给出了非格式化数字:
$total = WC()->cart->total;
// Testing output
var_dump($total);
如果使用 $total = WC()->cart->get_total("");
Note that, since WooCommerce 3, on other WooCommerce instance objects you can't access properties directly… But some few classes as
WC_Cart
still allow that.