0

I am trying to display the newly discounted price of line items inside my order emails (after editing it inside the actual order in wp-admin) - but using get_sale_price() gives me a critical error, is there something else I should be using?

I've tried the following, and each gives me either the regular price (before discount) or a critical error

$product->get_total(), $product->get_regular_price(), $product->get_price();

<?php foreach( $order->get_items() as $item_id => $item ) {

    $name = $item->get_name();
    $product = $item->get_product();
    $oldPrice = $product->get_subtotal();
    $price = $order->get_formatted_line_subtotal( $item );

    echo '<tr>';
    echo '<td>'.$name.'</td>';
    echo '<td>'.$oldPrice.'</td>';
    echo '<td>'.$price.'</td>';
    echo '</tr>';
} ?>

Thanks

MattHamer5
  • 1,431
  • 11
  • 21
  • 1
    Use `$item->get_subtotal()`or `$item->get_total()` instead of `$product->get_subtotal()` or `$product->get_total()` see [Get Order items and WC_Order_Item_Product in WooCommerce 3](https://stackoverflow.com/questions/45706007/get-order-items-and-wc-order-item-product-in-woocommerce-3) – LoicTheAztec Aug 04 '23 at 15:05

1 Answers1

0

The WC_Order_Item_Product class has a get_total() method which will give you the line total for the item after any discounts. The line total is the total amount for the line item, after any discounts. You can use this function to get the discounted price for each item in the order. Here is how to use it:

<?php 
foreach( $order->get_items() as $item_id => $item ) {

    $name = $item->get_name();
    $product = $item->get_product();
    $oldPrice = $product->get_regular_price();
    $price = $item->get_total(); // This gives the discounted price for this item

    // get_total() returns the total without formatting, so let's format it
    $formatted_price = wc_price($price);

    echo '<tr>';
    echo '<td>'.$name.'</td>';
    echo '<td>'.$oldPrice.'</td>';
    echo '<td>'.$formatted_price.'</td>';
    echo '</tr>';
} 
?>

wc_price() is used to format the price with your WooCommerce currency settings. This is usually a good idea when displaying prices to ensure they're formatted consistently and correctly.

Please note that $product->get_subtotal() is not a valid method, so it's replaced by $product->get_regular_price(), which will give the regular price of the product.