I am Using Wordpress version 4.9.4 with WooCommerce an WooCommerce Memberships plugin.
How can I get all users for specific membership plan ($memberships)?
Is there a hook or should I use raw query?
On the documentation, it says that plans / memberships are post type, so I tried to query this table:
SELECT jsu.id, jsu.user_email, jsu.display_name, jsp.post_title, jsp.post_type FROM `wp_users` jsu
LEFT JOIN `wp_posts` jsp ON (jsu.id = jsp.post_author)
LEFT JOIN `wp_usermeta` jsum ON (jsu.id = jsum.user_id)
WHERE jsp.post_title IN ($memberships) AND post_type = 'wc_membership_plan'
But I don't get the desired result.
I have made some changes in your SQL and set the code in an utility function:
function get_active_members_for_membership($memberships){
global $wpdb;
// Getting all User IDs and data for a membership plan
return $wpdb->get_results( "
SELECT DISTINCT um.user_id, u.user_email, u.display_name, p2.post_title, p2.post_type
FROM {$wpdb->prefix}posts AS p
LEFT JOIN {$wpdb->prefix}posts AS p2 ON p2.ID = p.post_parent
LEFT JOIN {$wpdb->prefix}users AS u ON u.id = p.post_author
LEFT JOIN {$wpdb->prefix}usermeta AS um ON u.id = um.user_id
WHERE p.post_type = 'wc_user_membership'
AND p.post_status IN ('wcm-active')
AND p2.post_type = 'wc_membership_plan'
AND p2.post_title LIKE '$memberships'
");
}
This code goes on function.php file of your active child theme (or theme). Tested and works.
USAGE:
// Replace 'My Membership' by your targeted membership name.
$users_data = get_active_members_for_membership('My Membership');
// Test raw output
echo '<pre>'; print_r( $users_data ); echo '</pre>';