Search code examples
phpwordpresswoocommerceorders

Display the product title by order number only in email notifications


I'm customizing my Woocommerce email templates now and right now I only have acess to the order number, I'd like to get the price and quantity for my order but I haven't managed to figure out how.

<?php 

    // Getting the order object "$order"

$order = wc_get_order( $order_id );

// Getting the items in the order

$order_items = $order->get_items();

// Iterating through each item in the order

foreach ($order_items as $item_id => $item_data) {

    // Get the item quantity, something is wrong here..

    $item_quantity = $order->get_item_meta($item_id, '_qty', true);
    echo $item_quantity;
    // Get the price, doesn't work either..
    $item_total = $order->get_item_meta($item_id, '_line_total', true)


}

?>

The issue is that I'm unable to get the quantity and price which I can display in my order confirmation email that I'm customizing, I'm currently running woocommerce 3.2.5


Solution

  • As you have the $order object, you can get the product title this way:

    <?php 
        // Loop through order items
        foreach($order->get_items() as $items){
            $product = $items->get_product(); // The product object
            $product_name = $product->get_name(); // The product Name
            $quantity = $items->get_quantity(); // The product Quantity
            $line_total = $items->get_total(); // The line item total
    
            // Display the product name
            echo '<p>'.$product_name.'</p>';
    
            // Display the product quantity
            echo '<p>'.$quantity.'</p>';
    
            // Display the product name
            echo '<p>'.$line_total.'</p>';
    
            // Get the raw output to check
            echo '<pre>'; print_r(echo $items->get_data() ); '</pre>';
        }
    ?>
    

    Remember that an order can have many items (so different product names).


    Related trhread: Get Order items and WC_Order_Item_Product in Woocommerce 3