在Woocommerce 3中获取产品价格

4

我正在尝试在自己创建的函数中获取不带货币符号的价格。

function add_price_widget()
{
    global $woocommerce;
    $product = new WC_Product(get_the_ID());
    $thePrice = $product->get_price_html();

    echo thePrice;
}

显示:100kr

如何让它只给我价格100

2个回答

8

如@Syntax_Error所说,你需要使用get_price(),WooCommerce也提供了一个包装函数wc_get_product()用于WC_Product类。

因此,你的函数应该像这样:

function add_price_widget()
{
    $product = wc_get_product(get_the_ID());
    $thePrice = $product->get_price(); //will give raw price
    echo $thePrice;
}

希望这有所帮助!

WooCommerce 4.5.1 - 这个版本存在问题。 - Ashwani Shukla
嗨@AshwaniShukla:我刚刚用WooCommerce 4.5.1进行了检查,没有收到任何错误。您可以请具体说明一下您所遇到的问题吗? - Raunak Gupta
未捕获的错误:调用未定义的方法 Automattic\WooCommerce\Admin\Overrides\Order::get_price() - Ashwani Shukla
@AshwaniShukla:我认为你遇到的问题是由于其他原因引起的,如果你查看这个链接 https://github.com/woocommerce/woocommerce/blob/master/includes/abstracts/abstract-wc-product.php#L266 ,get_price() 方法是存在的。 - Raunak Gupta

2
您只需使用函数get_price,该函数返回数字(不带点或符号)。
function add_price_widget() {
 global $woocommerce;
 $product = new WC_Product(get_the_ID()); 
 $thePrice = $product->get_price();
 echo thePrice;
}

我在我的网站上测试过了,它有效。所以它也应该对你有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接