I’m trying to remove some cookies set to control persistent login when the user specifically wants to log out of a website.
I thought it would be as simple as:
function remove_user_cookie() {
unset($_COOKIE['woai']);
unset($_COOKIE['woak']);
}
add_action('wp_logout', 'remove_user_cookie');
I’ve also tried:
function remove_user_cookie() {
if( $_GET['action'] == 'logout' ) :
unset($_COOKIE['woai']);
unset($_COOKIE['woak']);
endif;
}
add_action('wp_logout', 'remove_user_cookie');
However, the users cookies remain in place, so they keep getting logged back in automatically.
I’m not sure if the wp_logout action just isn’t working, or if it’s clashing with my code that logs the user in automatically.
Right now, I have this in the header.php:
<?php if( !is_user_logged_in() ) :
// check if user has cookies
if ( isset($_COOKIE['woai']) && isset($_COOKIE['woak']) ) :
$args = array(
'meta_key' => 'login_key',
'meta_value' => $_COOKIE['woak'],
'meta_compare' => '=',
'fields' => 'ID',
'include' => $_COOKIE['woai']
);
$user_query = new WP_User_Query($args);
if( $user_query->results[0] != '' || $user_query->results[0] != NULL ) :
// get user id and login name
$user_id = $user_query->results[0];
$user_login = get_user_by( 'id', $user_id );
// log the user in
wp_set_current_user( $user_id, $user_login->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user_login->user_login );
endif;
endif; // end if cookies
endif; ?>
And when the user is logged in, they get a new key set with this:
function set_user_cookie($user_login) {
// if they have cookies, delete them
if ( isset($_COOKIE['woai']) && isset($_COOKIE['woak']) ) :
unset($_COOKIE['woai']);
unset($_COOKIE['woak']);
endif;
$user_id = get_user_by( 'login', $user_login );
// generate new key for user
$salt = wp_generate_password(20); // 20 character "random" string
$key = sha1($salt . $email . uniqid(time(), true));
// set new cookies
setcookie("woai", $user_id->ID, time()+31536000); /* expire in 1 year */
setcookie("woak", $key, time()+31536000); /* expire in 1 year */
// update the db
update_field('field_53c3de9cd031e', $key, 'user_'.$user_id->ID.'');
}
add_action('wp_login', 'set_user_cookie', 10, 1);
2 Answers
pls try below code
function remove_user_cookie() {
setcookie("woak");
setcookie("woai");
}
add_action('wp_logout', 'remove_user_cookie');
apart why you use cookie to storing some value ? suggest you to use session