Reputation: 1243
I am trying to get a list of all users with active subscriptions, but for the life of me can't seem to get something working.
If I look at the users in the dashboard, I see all the active members have a "Abonné" role.
So I've set up my shortcode like this:
function custom_get_members( ){
$args1 = array(
'role' => 'Abonné',
'orderby' => 'user_nicename',
'order' => 'ASC'
);
$subscribers = get_users($args1);
$output = '<ul>';
foreach ($subscribers as $user) {
$output .= '<li>' . $user->display_name.'['.$user->user_email . ']</li>';
}
$output .= '</ul>';
return $output;
}
add_shortcode( 'annuaire', 'custom_get_members' );
But I always get 0 results, even though we have currently over 50 subscribers.
Running the WooCommerce with Subscription and Membership.
Thanks!
Upvotes: 3
Views: 3454
Reputation: 254019
Updated (with an additional customized function for your shortcode)
1) The following custom function that makes a very light SQL query will return an array of users Ids from all active subscribers:
function get_active_subscribers_ids(){
global $wpdb;
// Return an array of user Ids active subscribers
return $wpdb->get_col( "
SELECT DISTINCT pm.meta_value
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm
ON p.ID = pm.post_id
WHERE p.post_type = 'shop_subscription'
AND p.post_status = 'wc-active'
AND pm.meta_key = '_customer_user'
" );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
2) For your shortcode, I have changed this function to get directly the display_name
and user_email
:
function get_all_active_subscribers(){
global $wpdb;
return $wpdb->get_results( "
SELECT DISTINCT u.*
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm
ON p.ID = pm.post_id
JOIN {$wpdb->prefix}users as u
ON pm.meta_value = u.ID
WHERE p.post_type = 'shop_subscription'
AND p.post_status = 'wc-active'
AND pm.meta_key = '_customer_user'
" );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Usage in your shortcode:
function custom_get_members( ){
$output = '<ul>';
// Loop through active subscribers
foreach ( get_all_active_subscribers() as $user ) {
$output .= '<li>' . $user->display_name.'['.$user->user_email . ']</li>';
}
return $output . '</ul>';
}
add_shortcode( 'annuaire', 'custom_get_members' );
Tested and works with a much lighter query and code.
Upvotes: 8