Custom WordPress User Editing Restrictions
Do you remember how, in a recent post called “Let clients use the WordPress Dashboard“, I discussed the limitations inherent in the user management system in WordPress?
In a nutshell, if you use the Role Manager plugin to give a WordPress user who is fairly “senior” (but not an administrator) the ability to manage more “junior” user accounts, this means that they can also manage the administrator account – not an ideal situation if all they need to do is create subscriber users and send them emails from time to time. The system just isn’t granular enough. It’s a major security risk, and if they end up deleting your administrator account by mistake, things could get rather hairy.
In my earlier post I talked about my failure to find a plugin that could solve this by allowing certain roles to manage users in certain other roles, and I mentioned that I had started writing one myself.
Well, that particular development effort kind of tailed off due to lack of available time, but over the last couple of evenings I started thinking about the issue again, and took a bit of time to examine the PHP code that controls user management in the WordPress admin screens.
I realised that if I could get WordPress to check the roles of the current user and the user they were trying to edit before it displayed the user list with the edit and delete links, I would have an easy solution, albeit a core file hack (never ideal but probably the most pragmatic solution in this case).
To cut a long story short, here is my solution. All I needed to do was prevent non-administrators from editing administrator accounts, and this achieves exactly that.
In /wp-admin/includes/template.php, line 1899 looks like this:
if ( current_user_can( 'edit_user', $user_object->ID ) ) {
Replace it with this (without any line breaks):
if ((current_user_can( 'edit_user', $user_object->ID)) && (current_user_can('administrator') || (array_shift($user_object->roles) != 'administrator'))) {
That’s all there is to it.
Now I know that the non-admin user could probably still edit the administrator account by means of a hand-crafted URL, but my particular issue was about preventing accidents, not distrusting a user. So I’m pretty happy with this. I will have to make sure I re-implement it each time I update that particular WordPress installation, but I have my own system for making notes about that kind of thing, so it’s not a big hassle.
If you’re in a similar situation and want to try it, please take a backup of the file first, and please note that I have only implemented this on WordPress 2.8.4 – it will probably work on earlier (and indeed future) versions of WordPress, but the line number may be different.



That’s not a bad workaround – still not foolproof, of course, but a neat solution to the situation you faced.