Why does wp_redirect() is not working when i try use wp_signon() on custom login?

Viewed 24

I made my own custom login page then trying to login to that WP user's dashboard using wp_signon() function.

function custom_login()
{
    if (isset($_POST['submitlogin'])) {
        $login_data = array();
        $login_data['user_login'] = sanitize_user($_POST['txtEmail']);
        $login_data['user_password'] = $_POST['txtPass'];
        $user = wp_signon($login_data, false);

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

            wp_clear_auth_cookie();
            do_action('wp_login', $user->ID);
            wp_set_current_user($user->ID);
            wp_set_auth_cookie($user->ID, true);
            $redirect_to = 'https://www.google.com/';
            wp_redirect($redirect_to);
            exit;
        }
    }
}
custom_login();

After dumping wp_set_current_user($user->ID); I can see the user's data. enter image description here

1 Answers

Hook custom_login with init action or template_redirect action. You can redirect the page when content is already loaded.

Related