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:
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!
You could also do this,
Anonymous functions (closures), available in PHP 5.3+.
Benefits:
delete_user
wp_delete_user()
deleted_user
because we retain the user’s role within the function, hence we place our closure in theif(conditional)
statement.a)
delete_user
hook:Here is one idea:
Add this into your code to delete the user:
where we remove the action callback to prevent it calling it self again.
So your code becomes:
b)
deleted_user
hook:The
deleted_user
hook is activated after the user has been deleted, but not before as in thedelete_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: