wordpress wp_signon function not working
I am using wp_signon() function to login the user. I am doing this like
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
i want to send user to home page after login.
But i Am facin开发者_运维百科g following error:
Warning: Cannot modify header information - headers already sent by (output started at E:\xampp\htdocs\wpmoodle\wp-content\themes\twentyten\header.php:12) in E:\xampp\htdocs\wpmoodle\wp-includes\pluggable.php on line 690.
Thanks in advance.
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
, 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.
However, the error indicates that you've already sent some output -- on line 12 of header.php
, presumably some of the first HTML of the standard WordPress theme.
This basically indicates that you need to move your wp_signon()
call to somewhere earlier in the WordPress processing, so it has a chance to output its headers before any page content is sent.
If someone needs it, here is my solution:
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' );
精彩评论