How to get orders by user meta data in woocommerce?

by haylee.mertz , in category: PHP CMS , a month ago

How to get orders by user meta data in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a month ago

@haylee.mertz 

To get orders by user meta data in WooCommerce, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$meta_key = 'your_meta_key';
$meta_value = 'your_meta_value';

// Get all user IDs where meta key has the specified value
$user_ids = get_users(array(
    'meta_key' => $meta_key,
    'meta_value' => $meta_value,
    'fields' => 'ID'
));

// Get orders for each user
foreach ($user_ids as $user_id) {
    $orders = wc_get_orders(array(
        'customer' => $user_id,
        'status' => array('processing', 'completed') // Specify order statuses if needed
    ));

    // Output order data
    foreach ($orders as $order) {
        // Output order data here
    }
}


Replace 'your_meta_key' and 'your_meta_value' with the actual meta key and value you want to filter orders by. This code snippet will first get a list of user IDs that have the specified meta data, and then get orders for each user based on the customer ID.