How to Prevent deleting user accounts in WordPress Back-end?

The question:

I have tried to find similar question. And I have not get any existing one. I want to prevent deleting administrators from the back end users table. only two admins can delete all users, But other admins cant delete all other administrators. I have tried this code. But if i go with direct url parameters, its allowing me to delete the user.

function kv_admin_deactivate_link($actions, $user_object) {

    if($user_object->ID == 1 || $user_object->ID == 2) 
        unset($actions['delete']);

    return $actions;
}
add_filter('user_row_actions', 'kv_admin_deactivate_link', 10, 2);

which actually helps to hide the delete link from the users table. but if i go with direct GET link its allowing me to delete.

So is there any function or feature, which will prevent the deletion.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

A quick (and dirty) solution would be to prevent the final deletion where it happens (function delete_user). You could implement a little plugin or paste the code into your functions.php:

<?php

/*
Plugin Name: Please don't delete me!
Description: Prevent accidental user deletion of my account
*/

define('PDDM_USER_ID', 1); // User ID of your Account

add_action('delete_user', function($id) {
    if ($id == PDDM_USER_ID) {
        die('please don't delete me!');
    }
});

This just stops the script execution just before your user get’s deleted.

Not fancy and pretty … but it works 😉

br from Salzburg!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment