Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set cookie before log out and after admin login

Hi I am new to wordpress.

I had researched lot about this but didn't succeed. I want to set cookie value NULL before logout and custom value after admin logged in.

So I put below code in wp-includes/puggable.php => in the function wp_set_auth_cookie

setcookie("cookieName", '', time() + (1 * 60) , true);

echo "<script>console.log('Cookie must set null')</script>";

But didn't get succeed cookie value remain same even after login-logout.

like image 958
Jaydeep Pandya Avatar asked Dec 14 '22 11:12

Jaydeep Pandya


1 Answers

NEVER edit Wordpress core files! If you update Wordpress one day (and you'll want to, as to fix the security issues), all your modifications will be lost.

What you need to do is to work with the wp_login and wp_logout actions. You attach on both of those actions functions with add_action, so they will be triggered on those events. Those functions and the add_action calls take place inside the functions.php file of your theme.

So inside functions.php, add this to set the cookie on login (for admin only):

add_action('wp_login', 'add_custom_cookie_admin');
function add_custom_cookie_admin() {
  if(current_user_can('update_core')) {
    setcookie('your_cookie_name', 'cookie value', time() + 86400, '/'); // expire in a day
  }
}

Note that as diziaq pointed out in his answer, you was using wrong the setcookie function.

And to delete the cookie on log out:

add_action('wp_logout', 'remove_custom_cookie_admin');
function remove_custom_cookie_admin() {
  setcookie('your_cookie_name', '', time() - 3600);
}

Same as diziaq pointed out, you need to remove the cookie - you can't set it to NULL.

like image 132
vard Avatar answered Jan 07 '23 19:01

vard