Very recently, I had a situation where I needed to take user's username and password as inputs and log him/her onto Wordpress manually. And this is how I came up with the solution. Check the code below.
<?php
// This is a very important step
// We need to get the wp object
require("wp-load.php");
// Log Out if anyone is already logged
// in from same browser
if ( is_user_logged_in() )
{
// Default Wordpress function
// to log a user out
wp_logout();
}
// GET user's Inputs (username, password)
$creds = array();
$creds['user_login'] = $_POST['username'];
$creds['user_password'] = $_POST['password'];
// Extra settings, for Remember me
$creds['remember'] = false;
// The Wordpress function which Logs
// the user in
$user = wp_signon( $creds, false );
// Track ERROR if any
if ( is_wp_error($user) )
{
echo $user->get_error_message();
}
// Login Success
else
{
echo "You have logged in successfully";
}
?>
The code above is quite self-explanatory. Some points to be noted :
1. wp_signon() -- It logs any user in with username and passwords passed to it in Array. This function takes a 2nd parameter to mention whether secured cookies are to be used.
2. wp_logout() -- It logs out if any user is logged in
3. The array $cred must be built with the keys ('user_login' and 'user_password') shown above.
<?php
// This is a very important step
// We need to get the wp object
require("wp-load.php");
// Log Out if anyone is already logged
// in from same browser
if ( is_user_logged_in() )
{
// Default Wordpress function
// to log a user out
wp_logout();
}
// GET user's Inputs (username, password)
$creds = array();
$creds['user_login'] = $_POST['username'];
$creds['user_password'] = $_POST['password'];
// Extra settings, for Remember me
$creds['remember'] = false;
// The Wordpress function which Logs
// the user in
$user = wp_signon( $creds, false );
// Track ERROR if any
if ( is_wp_error($user) )
{
echo $user->get_error_message();
}
// Login Success
else
{
echo "You have logged in successfully";
}
?>
The code above is quite self-explanatory. Some points to be noted :
1. wp_signon() -- It logs any user in with username and passwords passed to it in Array. This function takes a 2nd parameter to mention whether secured cookies are to be used.
2. wp_logout() -- It logs out if any user is logged in
3. The array $cred must be built with the keys ('user_login' and 'user_password') shown above.
No comments:
Post a Comment