WordPress login programmatically with user name/cookies

Solution:1

you should write your code to functions.php file. Also, you should put your codes in pieces for invoke it. I write code again but I think there are some parts to fix.

add_action( 'init', 'setting_my_first_cookie' );

function setting_my_first_cookie() {

if(isset($_COOKIE['xxx'])) {
    $user_email = $_COOKIE['xxx'];
    $decrypted = simple_decrypt($user_email);

if( !email_exists( $decrypted )){
    wp_create_user( $decrypted, $user_email . $user_email , $decrypted );
}
if(!is_user_logged_in()){
    $username = $decrypted;
    $user = get_user_by('login', $username );

    clean_user_cache($user->ID);
    wp_clear_auth_cookie();
    wp_set_current_user($user->ID);
    wp_set_auth_cookie($user->ID, true, false);
    update_user_caches($user);

        echo ("
        <script>
            console.log('".  wp_set_auth_cookie($user->ID, true, false) ."')
        </script>
        ");
        }
    }
    else {
        return "You are not authenticated for seeing this page!";
    }
}

Solution:2

Use following code

<?php

function auto_login( $user ) {
$username = $user;
// log in automatically
if ( !is_user_logged_in() ) {
$user = get_userdatabylogin( $username );
$user_id = $user->ID;
wp_set_current_user( $user_id, $user_login );
wp_set_auth_cookie( $user_id );
do_action( ‘wp_login’, $user_login );
}
}
?>