Woocommerce - Getting the order item price and quantity.

人走茶凉 提交于 2019-12-02 19:15:30

Update (For WooCommerce 3+)

Now for the code you can use WC_Order_Item_Product (and WC_Product) methods instead, like:

## For WooCommerce 3+ ##

// Getting an instance of the WC_Order object from a defined ORDER ID
$order = wc_get_order( $order_id ); 

// Iterating through each "line" items in the order
foreach ($order->get_items() as $item_id => $item_data) {

    // Get an instance of corresponding the WC_Product object
    $product = $item_data->get_product();
    $product_name = $product->get_name(); // Get the product name

    $item_quantity = $item_data->get_quantity(); // Get the item quantity

    $item_total = $item_data->get_total(); // Get the item line total

    // Displaying this data (to check)
    echo 'Product name: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. number_format( $item_total, 2 );
}

This code is tested and works.

Method get_item_meta() is deprecated and has been replaced by wc_get_order_item_meta and it's not anymore a method but a function with some parameters:

/** Parameters summary
 * @param mixed $item_id
 * @param mixed $key
 * @param bool $single (default: true)
 * @return mixed
 */

wc_get_order_item_meta( $item_id, $key, $single = true );

Prior versions of woocommerce (from 2.4 to 2.6.x)

You can use get_item_meta() WC_Abstract_order method, to get the order metadata (the item quantity and the item price total).

So your code will be:

// 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 product name
    $product_name = $item_data['name'];
    // Get the item quantity
    $item_quantity = $order->get_item_meta($item_id, '_qty', true);
    // Get the item line total
    $item_total = $order->get_item_meta($item_id, '_line_total', true);

    // Displaying this data (to check)
    echo 'Product name: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. $item_total;
}

This code is tested and fully functional.

Reference: Class WC_Abstract_Order Methods

Item price can get from order object by below code

$order->get_item_total( $item );

Please see this documentation for woocommerce Line item in order class. Here

You can call total for get the total order cost. If you want to retrieve the single item cost by taking the product_id

$_product = wc_get_product( $product_id );
$Price = $_product->get_price();

Or you can do this.

$price = get_post_meta( get_the_ID(), '_regular_price', true);
$price = get_post_meta( get_the_ID(), '_sale_price', true);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!