0

I am using plugin for login/logout(https://wordpress.org/plugins/login-logout-menu/) navigation link to be dynamic. Once user role logged in they will redirect to specific page and functionality is working fine. For logged out it should redirect to home page for specific role. I have tried using the hooks provided but it is not working. Currently admin and normal user role logged out to the default login redirect link which is in the wordpress.

 function redirect_after_logout() {

        $current_user   = wp_get_current_user();
        $role_name      = $current_user->roles[0];

        if($role_name == 'employee'){
            $redirect_url = site_url();
            wp_safe_redirect( $redirect_url );
            exit;
        } 

    }
    add_action( 'wp_logout', 'redirect_after_logout'  );

1 Answer 1

1

The wp_logout action fires after the user is logged out. They no longer have a role.

However, since WordPress 5.5.0, the hook takes one parameter: the ID of the user who is being logged out. So you might be able to accomplish your goal by using that ID instead of wp_get_current_user().

function redirect_after_logout( $user_id ) {

    $current_user   = get_user_by( 'id', $user_id );
    if ( empty( $current_user ) || empty( $current_user->roles ) ) {
        return;
    }
    $role_name      = $current_user->roles[0];

    if($role_name == 'employee'){
        $redirect_url = site_url();
        wp_safe_redirect( $redirect_url );
        exit;
    } 

}
add_action( 'wp_logout', 'redirect_after_logout'  );

If you're not using at least WordPress 5.5.0, this won't work (and you should probably update, too).

References

4
  • Is there a reason ` $role_name = $current_user->roles[0];` would throw the warning Trying to access array offset on value of type null?
    – Motivated
    Oct 28, 2023 at 2:36
  • Hmm, the code wasn't checking to see if $current_user->roles existed; I've added a quick update to the code to (hopefully) fix the issue.
    – Pat J
    Oct 28, 2023 at 3:04
  • Thanks. Should it be checking if it exists?
    – Motivated
    Oct 28, 2023 at 3:37
  • It's never a bad idea to check a variable to make sure it's what you expect — eg. an array and not false.
    – Pat J
    Oct 28, 2023 at 3:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.