Finding WordPress Administrator User IDs

I’ve been adding a couple of new features to Post Ideas+ over the past few days. One feature in particular required knowing the ID’s of users with the role of ‘administrator’. Now usually you can assume that the ID will be 1, as that’s what the initial adimin account setup by WordPress on install gets assigned. But as the code is going to be used in a plug-in you can’t really assume that.

Some people may have deleted the default account for security reasons (very good idea) or they have more that one administrator account. After hunting about on the WordPress forums for a while I managed to piece together a little snippet of code to do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Get all admin user ID's in the DB
function admin_user_ids(){
    //Grab wp DB
    global $wpdb;
    //Get all users in the DB
    $wp_user_search = $wpdb->get_results("SELECT ID, display_name FROM $wpdb->users ORDER BY ID");

    //Blank array
    $adminArray = array();
    //Loop through all users
    foreach ( $wp_user_search as $userid ) {
        //Current user ID we are looping through
        $curID = $userid->ID;
        //Grab the user info of current ID
        $curuser = get_userdata($curID);
        //Current user level
        $user_level = $curuser->user_level;
        //Only look for admins
        if($user_level >= 8){//levels 8, 9 and 10 are admin
            //Push user ID into array
            $adminArray[] = $curID;
        }
    }
    return $adminArray;
}

//Usage
$adminIdArray = $this->admin_user_ids();

I placed it into it’s own function within my plug-in Class so it can be called whenever needed. It could also be used for finding users with different levels in WordPress if needed. If you wanted you could modify the function to accept an argument admin_user_ids($the_user_level_i_need); allowing you to get the IDs of users at whatever level you like.

There seemed to be a few ways of doing this on the forums, but this one works for me at the moment.

Loading

Webmentions