0

I am using a custom login form on a site and I'm having trouble with redirecting admins to the dashboard automatically.

Below is the login function

function auth( $username, $password, $redirect ) {
    global $user;

    $credentials = array();
    $credentials ['user_login'] = $username;
    $credentials ['user_password'] =  $password;
    $credentials ['remember'] = true;
    $user = wp_signon( $credentials , false );

    if ( is_wp_error($user) )
    {
        echo $user->get_error_message();
    }

    $admin_url = home_url('wp-admin');

    if ( !is_wp_error($user) )
    {
        if (current_user_can('administrator'))
        {
            wp_redirect($admin_url);
        }
        else
        {
            wp_redirect($redirect);
        }
    }
}

When I log in as the admin, current_user_can('administrator') is returning false.

If I step into the current_user_can() function, $current_user = wp_get_current_user(); seems to fetch some data, but looks like it's not getting everything, hence the false response.

I also tried using is_admin() but that doesn't work either.

1

the current user may not be set at this step then try this :

    if (user_can($user, 'administrator'))
    {
        wp_redirect($admin_url);
    }
  • Works, lovely :) Wodner why the current user isn't setup despite using wp_signon()? – Mr Pablo Oct 12 '16 at 13:49
  • current user is based on the cookie which doesn't exist. it exist only on reload of a page – mmm Oct 12 '16 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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