我正在寻找一种在WooCommerce中获取订单商品单价的方法。我在这里关注了这篇文章,并使用了get_price()
方法,但是该方法似乎不再可用:
Woocommerce - Getting the order item price and quantity.
foreach ( $order_items as $order_item ) {
error_log( $order_item->get_price() );
error_log( print_r( $order_item, true ) );
}
未捕获的错误:调用未定义的方法 WC_Order_Item_Product :: get_price()
问题是我不能只从那里获取产品并读取正常价格,因为我需要在下订单时设置价格,并且以后可以多次更改产品价格。
我还打印了整个订单商品,以在其中找到单个价格字段,但一无所获:
[data:protected] => Array
(
[order_id] => 24
[name] => Dings Teil
[product_id] => 23
[variation_id] => 0
[quantity] => 2
[tax_class] =>
[subtotal] => 42.4
[subtotal_tax] => 6.78
[total] => 42.4
[total_tax] => 6.78
[taxes] => Array
(
[total] => Array
(
[6] => 6.784
)
[subtotal] => Array
(
[6] => 6.784
)
)
)
总而言之,我需要某种方式从我的订单商品中获得单个价格。 WooCommerce似乎有一种在订单项视图中获取它的方法,但我找不到他们处理此问题的方法:
因为我正在编写一个插件,所以对WooCommerce的任何更改都不是一个好主意。
更新:
是的,我也有将小计除以数量的想法,但是在我的舍入不是100%像WooCommerce舍入的情况下,这可能会导致一些舍入问题。
答案 0 :(得分:2)
get_price()
类使用方法WC_Product
……请改用以下内容:
foreach ( $order->get_items() as $item ) {
$product = $item->get_product(); // Get the WC_Product Object
$price = $product->get_price();
error_log( $price );
error_log( print_r( $order_item, true ) );
}
应该更好地工作。
您还可以使用以下内容(按数量将商品小计):
foreach ( $order->get_items() as $item ) {
$quantity = $item->get_quantity(); // Quantity
$subtotal = $item->get_subtotal(); // Line subtotal
$subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax
$price_excl_tax = $subtotal / $quantity;
$price_incl_tax = ( $subtotal + $subtotal_tax ) / $quantity
error_log( 'Price without tax: ' . $price_excl_tax );
error_log( 'Price with tax: ' . $price_incl_tax );
}