I am working on WordPress multisite, and I have changed the login functionality. However, it needs the users to delete old cookies before using this functionality I have created. So I am trying to clear the user’s cookies by setting a new cookie, custom_wordpress_login_cookie
, to know which of the users have old cookies in the browser, as shown in the following code.
add_action('init', 'clear_all_cookies_before_login');
function clear_all_cookies_before_login(){
if( ! isset( $_COOKIE['custom_wordpress_login_cookie'] ) ){
foreach( $_COOKIE as $key => $value ){
setcookie( $key, '', time() - YEAR_IN_SECONDS);
}
setcookie( 'custom_wordpress_login_cookie', 'true',
time() + YEAR_IN_SECONDS, '/', COOKIE_DOMAIN, false, true );
}
}
The new cookie is being set, but the old cookies persist. What could be the issue?
6
Answers
you must used first unset
Once that’s done, we will force the cookie to expire by setting its value variable to a null value (“”) and passing in a timestamp that’s in the past (time() – ( 15 * 60 )).
To prevent creation of a second cookie with the same name, pass
/
as the path argument tosetcookie()
.And so, you must change this line:
to:
Also note that the way you’re expiring cookies may not work if the user’s system time is configured incorrectly. This is rare*, but does happen. A simpler way to expire cookies is to simply call:
*the user would likely run into TLS issues if the webpage is served over HTTPS.
This is not an answer related to how you can clear cookies, but this solution will help you make sure that all the users currently logged into your website will need to login again.
Go in the wp-config.php and reset the secret salt keys. You can generate new ones here: https://api.wordpress.org/secret-key/1.1/salt/ .
That way it will force all of your users to login again and you no longer need to write code to delete the users’ cookies.
You are doing absolutely correct but the deletion of the cookie would not work. The above code will only expire the cookie in the current session. You have to destroy the session also if you want to make the old cookie dis-appear. Thus your new code would be like this:
Try:
setcookie( $key, '', time() - 3600, '/', COOKIE_DOMAIN);
According WordPress documentation, it combines the salt keys with the password. The hash function mixes these up and gives a result. After that it stores inside a cookie to "remember" the login process or tracking behavior.
example: That’s the reason two different usernames with the same password are successfully identified as different logins.
First you have to make distinct cookies for every user. Let’s say custom_wordpress_login_cookie will contain inside a string with the username or any associated encoded string (preferred).
Then you will check if the custom_wordpress_login_cookie exists and contains the appropriate username.
Act accordingly, if found, perform your logic and then delete (unset) the cookie. Else create a new one.
The following code explains the flow…