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!
2 Answers
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 theif(conditional)
statement.