2
votes

I'm looking for a way to get the single price of an order item in WooCommerce. I've followed this post here and used the get_price() method but this method seems to be not available anymore:

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 ) );
}

Uncaught Error: Call to undefined method WC_Order_Item_Product::get_price()

The problem is that I can't just get the product and read the normal price there because I need the price set during the order placement and a product price can be changed later a lot of times.

I've also printed out the whole order item to find the single price field there but found nothing:

[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
                    )
            )
    )

So all in all I need the single price from my order item somehow. WooCommerce seems to have a way getting it in the order items view but I can't find the way they deal with this:

enter image description here

Because I'm writing a plugin, any WooCommerce changes are not a good idea at all.

Update:

Yes, I've also had the idea dividing the subtotal by the quantity but this may cause some rounding problems in the case my rounding is not 100% like the WooCommerce rounding.

1

1 Answers

2
votes

The method get_price() is used by the WC_Product Class… Use the following instead:

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 ) );
}

It should better work.


You can also use the following (dividing item subtotal by quantity):

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 );
}