Chandrakant
Chandrakant

Reputation: 111

How to retrieve email addressess of users with specific role in WordPress through this code

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

Answers (3)

Howdy_McGee
Howdy_McGee

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

RRikesh
RRikesh

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

Pawan Developers
Pawan Developers

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

Related Questions