在 WooCommerce 中获取购物车总计非格式化值作为浮点数
Get the cart totals non formatted values as float numbers in WooCommerce
我怎样才能得到购物车total/total_ex_tax as float number?
我找过,但所有的答案都是这样的:
a) 丑陋的用法 reg_exp(例如,如果我们要使用 ',' 而不是 '.' 会怎样?):
global $woocommerce;
$amount = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) );
b) 直接访问 class 属性(将来可能会更改;而不是 OOP 方法)。它有效,但这是一种错误的方式:
global $woocommerce;
echo $woocommerce->subtotal;
echo $woocommerce->subtotal_ex_tax;
echo $woocommerce->total;
echo $woocommerce->total_ex_tax;
echo $woocommerce->cart_contents_total;
我想变得正常 API 像这样:
$wc = WC();
echo $wc->cart->get_total_as_number();
echo $wc->cart->get_total_ex_tax_as_number();
使用 WC()->cart
(WC_Cart
class 对象)您可以使用以下 WC_Cart
class documentation Api 中列出的方法或访问属性。
因此,使用 WC()->cart
,您可以直接访问 属性 并使用以下方法获取 非格式化值 :
echo WC()->cart->subtotal;
echo WC()->cart->subtotal_ex_tax;
echo WC()->cart->total;
echo WC()->cart->total_ex_tax;
echo WC()->cart->cart_contents_total;
您将获得浮点数。请记住 WC()->cart
是一个活动对象。
WC()->cart
replace totally global $woocommerce;
with $woocommerce->cart
, so no need to use outdated global $woocommerce;
with it…
我怎样才能得到购物车total/total_ex_tax as float number?
我找过,但所有的答案都是这样的:
a) 丑陋的用法 reg_exp(例如,如果我们要使用 ',' 而不是 '.' 会怎样?):
global $woocommerce;
$amount = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) );
b) 直接访问 class 属性(将来可能会更改;而不是 OOP 方法)。它有效,但这是一种错误的方式:
global $woocommerce;
echo $woocommerce->subtotal;
echo $woocommerce->subtotal_ex_tax;
echo $woocommerce->total;
echo $woocommerce->total_ex_tax;
echo $woocommerce->cart_contents_total;
我想变得正常 API 像这样:
$wc = WC();
echo $wc->cart->get_total_as_number();
echo $wc->cart->get_total_ex_tax_as_number();
使用 WC()->cart
(WC_Cart
class 对象)您可以使用以下 WC_Cart
class documentation Api 中列出的方法或访问属性。
因此,使用 WC()->cart
,您可以直接访问 属性 并使用以下方法获取 非格式化值 :
echo WC()->cart->subtotal;
echo WC()->cart->subtotal_ex_tax;
echo WC()->cart->total;
echo WC()->cart->total_ex_tax;
echo WC()->cart->cart_contents_total;
您将获得浮点数。请记住 WC()->cart
是一个活动对象。
WC()->cart
replace totallyglobal $woocommerce;
with$woocommerce->cart
, so no need to use outdatedglobal $woocommerce;
with it…