Here is my working solution:
function custom_login() {
if(!empty($_POST['user_login']) && !empty($_POST['user_pass'])){
$login_data = array();
$login_data['user_login'] = sanitize_user($_POST['user_login']);
$login_data['user_password'] = esc_attr($_POST['user_pass']);
$login_data['rememberme'] = true;
$nonce = $_REQUEST['_wpnonce'];
$user = wp_signon( $login_data, false );
global $user_ID;
// Check whether the user is already logged in and the nonce is verified
if ( !$user_ID && !wp_verify_nonce( $nonce, 'wp_login' ) ) {
exit;
} else {
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);
wp_safe_redirect(home_url());
exit;
}
}
}
}