How to get woocommerce orders by user id in wordpress?
Aspirant Programmer

How to get all orders made by a user in woocommerce using SQL query?

  • Total 1 Answer
  • 2417
Can You answer this question?
Aspirant Programmer

You can get same solution by using woocommerce built in functions. But this is the way which is independent of the woocommerce versions. Just paste the below function and get all orders made by a particular user by just providing user id. If you check the sql query, you will realize how many tables are involved to fetch the orders and how the records are stored into database. So it is also usefull to understand database structure of woocommerce orders.

//Get orders by user id
function get_orders($user_id)
    global $wpdb;
    $querystr = "select
       p.ID as order_id,
       max( CASE WHEN im.meta_key = '_product_id' and i.order_item_id = im.order_item_id THEN im.meta_value END ) as Prod_ID
       wp_posts as p,
       wp_postmeta as pm,
       wp_woocommerce_order_items as i,
       wp_woocommerce_order_itemmeta as im
       p.post_type = 'shop_order'
       and p.ID = pm.post_id
       and p.ID = i.order_id
       and pm.meta_key = '_customer_user'
       and pm.meta_value = $user_id";

    $orders = $wpdb->get_results($querystr, OBJECT);
    return $orders;