Protect Specific Users From Editing and Deletion
Stops anyone but the users themselves from editing, demoting or deleting the accounts you list, such as the site owner or an agency account.
Opens WPIDE on
Code
// IDs of protected users. Find an ID by hovering the user's name on the Users screen.
$wpide_protected_users = array( 1 );
add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) use ( $wpide_protected_users ) {
if ( ! in_array( $cap, array( 'edit_user', 'delete_user', 'remove_user', 'promote_user' ), true ) || empty( $args[0] ) ) {
return $caps;
}
$target = (int) $args[0];
if ( in_array( $target, array_map( 'intval', $wpide_protected_users ), true ) && $target !== (int) $user_id ) {
$caps[] = 'do_not_allow';
}
return $caps;
}, 10, 4 );
Notes
Protected users can still edit their own profile.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.