I am using WooCommerce for my ecommerce site.I am trying to sort users by recent order made by their account. Is there any method for doing this? like passing parameters on get_users()
You can use this custom light SQL query embedded in a function which will return an array of customers IDs sorted by most recent orders date (for orders status "completed" and "processing"):
function get_users_by_orders_date(){
global $wpdb;
// Getting all User IDs by more recent orders
return $wpdb->get_col( "
SELECT DISTINCT pm.meta_value
FROM {$wpdb->prefix}postmeta AS pm
JOIN {$wpdb->prefix}posts AS p ON pm.post_id = p.ID
WHERE pm.meta_key LIKE '_customer_user'
AND p.post_type = 'shop_order'
AND p.post_status IN ('wc-completed','wc-processing')
ORDER BY p.post_date
" );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Usage in your code:
$user_ids = get_users_by_orders_date(); // Array of user IDs