Skip to content

Instantly share code, notes, and snippets.

@mitchelldmiller
Created January 7, 2019 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchelldmiller/9123d28d0eed2ddeeb25275989afef87 to your computer and use it in GitHub Desktop.
Save mitchelldmiller/9123d28d0eed2ddeeb25275989afef87 to your computer and use it in GitHub Desktop.
get email addresses for a WordPress role.
<?php
// get email addresses for a role.
// Usage: http://example.com/qm_wp_roles.php?role=author
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';
header( 'Content-type: text/plain' );
$input = empty( $_GET['role'] ) ? '' : strtolower( $_GET['role'] );
if ( empty( $input ) ) {
echo qm_show_usage();
exit;
} // end if missing role
if ( ! qm_valid_role( $input ) ) {
echo qm_show_roles();
exit;
} // end if invalid role
$results = qm_get_role_email( $input );
if ( empty( $results ) ) {
echo "No users with role: {$input}\r\n";
} else {
echo "To {$input}: {$results}\r\n";
} // end if no results.
exit; // The end.
function qm_show_usage() {
return "Usage: http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}?role=wp_role\r\n";
} // end qm_get_usage.
function qm_show_roles() {
$lf = "\r\n";
$text = "Valid Roles{$lf}";
$roles = qm_get_roles();
foreach ( $roles as $role ) {
$text .= "{$role}{$lf}";
} // end foreach
return $text;
} // qm_show_roles
function qm_valid_role( $input ) {
$roles = qm_get_roles();
return in_array( $input, $roles );
} // end qm_valid_role
function qm_get_roles() {
global $wp_roles;
$data = array();
foreach ( $wp_roles->roles as $key => $value ) {
$data[] = $key;
} // end foreach
sort( $data );
return $data;
} // end qm_get_roles
function qm_get_role_email( $input ) {
$args = array(
'role' => $input,
'fields' => array( 'user_email' ),
);
$user_query = new WP_User_Query( $args );
$j = count( $user_query->results );
if ( empty( $j ) ) {
return '';
} // end if no match.
$got = '';
for ( $i = 0; $i < $j; $i++ ) {
$got .= $user_query->results[ $i ]->user_email . ',';
} // end for
return substr( $got, 0, -1 );
} // end qm_get_role_email
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment