Reputation: 111
I am able to retrieve email addresses of all the users in WordPress with the help of this code:
<?php
$users = get_users();
foreach ($users as $user ) {
$email = get_user_meta($user->ID, "email", true);
?>
I would like to retrieve the email addresses of users only with Subscriber role (slug = subscriber) by modifying the above code.
Please advice.
Upvotes: 0
Views: 2505
Reputation: 10663
I like to use a combination of get_users()
and wp_list_pluck()
. It looks like this:
$users = get_users( array( 'role' => 'subscriber' ) );
if( ! empty( $users ) ) {
$emails = wp_list_pluck( $users, 'user_email' );
}
Upvotes: 0
Reputation: 14381
get_users()
allows you to query by a specific role:
$users = get_users( array( 'role' => 'subscriber' ) );
foreach ( $users as $user ) {
$email = get_user_meta($user->ID, "email", true);
echo $email;
}
Upvotes: 2
Reputation: 377
you can try this code:
<?php
$users = get_users();
foreach ($users as $user ) {
if ( in_array( 'subscriber', (array) $user->roles ) ) {
$email = get_user_meta($user->ID, "email", true);
}
}
?>
Upvotes: 0