WordPress Login with Code

wp_signon( array $credentials = array(), string|bool $secure_cookie = '' );
function custom_login() {
    if (isset($_POST['submit'])) {
        $login_data = array();
        $login_data['user_login'] = sanitize_user($_POST['username']);
        $login_data['user_password'] = esc_attr($_POST['password']);

        $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 = $_SERVER['REQUEST_URI'];
            wp_safe_redirect($redirect_to);
            exit;
        }
    }
}

add_action( 'after_setup_theme', 'custom_login' );

https://stackoverflow.com/questions/5335833/wordpress-wp-signon-function-not-working/

wp_signon() needs to run before you've sent any of your actual page to the browser.

This is because part of what wp_signon() does is to set your authentication cookies. It does this by outputting a "Set-Cookie: ..." header -- if you look at line 690 of pluggable.php (wp-includes\pluggable.php), where your error comes from, you'll see that that line sets a cookie.

So, because wp_signon() outputs headers, you can't already have sent any content -- because headers must always be output before content.



Leave a Reply