Get Order ID from Current Custom Orders in WooCommerce

Here is the situation. I have a woocommerce site used as a market. I sell games on it because some buyers get a steam key. To do this, I’m working on a key attribution system, therefore, going to the page, the key will be an attribute for the user.

To do this, I want to check all the orders made by the current user (at the login and on the page), and check the game that he bought.

I find here very useful information: How to get WooCommerce order details

However, I am unable to receive all orders of the current user. I first think to make a SQL query, but I did not find a link in the database between the order and the user.

Do you have leadership?

+4
source share
1 answer

Updated Added compatibility with WooCommerce 3+ (January 2018)

Here is the code that you will need to receive all customer orders and view all the items on each customer order:

## ==> Define HERE the statuses of that orders 
$order_statuses = array('wc-on-hold', 'wc-processing', 'wc-completed');

## ==> Define HERE the customer ID
$customer_user_id = get_current_user_id(); // current user ID here for example

// Getting current customer orders
$customer_orders = wc_get_orders( array(
    'meta_key' => '_customer_user',
    'meta_value' => $customer_user_id,
    'post_status' => $order_statuses,
    'numberposts' => -1
) );


// Loop through each customer WC_Order objects
foreach($customer_orders as $order ){

    // Order ID (added WooCommerce 3+ compatibility)
    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    // Iterating through current orders items
    foreach($order->get_items() as $item_id => $item){

        // The corresponding product ID (Added Compatibility with WC 3+) 
        $product_id = method_exists( $item, 'get_product_id' ) ? $order->get_product_id() : $item['product_id'];

        // Order Item meta data
        $item_meta_data = wc_get_order_item_meta( $item_id );

        // TES: Some output
        echo '<p>Line total for '.wc_get_order_item_meta( $item_id, '_line_total', true ).'</p><br>';
    }
}

This code has been verified and works.


on this topic:

+9
source

Source: https://habr.com/ru/post/1669684/


All Articles