Redirect After Delete User in Backend

How do I redirect to a certain page after user deletion?

For demonstration purpose, let’s say I want to redirect to the dashboard on user subscriber deletion. This is what I have tried so far:

Read More
function mod_redirect_subscriber_delete($user_id) {
  $user  = get_user_by('id', $user_id);
  $role   = $user->roles[0];
  if ($role == 'subscriber') {
    wp_redirect( admin_url('/index.php') );
    exit;
  }
}
add_action("delete_user", "mod_redirect_subscriber_delete");

The above code successfully redirected me to the dashboard, but the user didn’t get deleted.

I had also tried deleted_user. This deleted the user but it didn’t redirect.

Any ideas?

Cheers!

Related posts

2 comments

  1. You could also do this,

    function mod_redirect_subscriber_delete($user_id) {
      $user  = get_user_by('id', $user_id);
      $role   = $user->roles[0];
      if ($role == 'subscriber') {
        add_action("deleted_user", function(){
            wp_redirect( admin_url('/index.php') );
            exit;
        });
      }
    }
    add_action("delete_user", "mod_redirect_subscriber_delete");
    

    Anonymous functions (closures), available in PHP 5.3+.

    Benefits:

    • No need to remove the initial hook on delete_user
    • No need to re-run wp_delete_user()
    • You still get to hook onto deleted_user because we retain the user’s role within the function, hence we place our closure in the if(conditional) statement.
  2. a) delete_user hook:

    Here is one idea:

    Add this into your code to delete the user:

    remove_action("delete_user", "mod_redirect_subscriber_delete");
    wp_delete_user($user_id);
    

    where we remove the action callback to prevent it calling it self again.

    So your code becomes:

    function mod_redirect_subscriber_delete($user_id) {
      $user  = get_user_by('id', $user_id);
      $role   = $user->roles[0];
      if ($role == 'subscriber') {
    
        // start extra:
        remove_action("delete_user", "mod_redirect_subscriber_delete");
        wp_delete_user($user_id);
        // end extra
    
        wp_redirect( admin_url('/index.php') );
        exit;
      }
    }
    add_action("delete_user", "mod_redirect_subscriber_delete");
    

    b) deleted_user hook:

    The deleted_user hook is activated after the user has been deleted, but not before as in the delete_user case.

    That means you can’t check the role of the user, since it has been deleted.

    You could use it like this, but for all users:

    function mod_redirect_subscriber_deleted($user_id) {
       wp_redirect( admin_url('/index.php') );
       exit();
    }
    add_action("deleted_user", "mod_redirect_subscriber_deleted");
    

Comments are closed.