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.

Read More

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.

Related posts

2 comments

  1. 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.

  2. Please read docs for setcookie function – you use it wrong. The fourth parameter must be a string (but you’re passing a bool).

    1. To set a cookie:

      setcookie("cookieName", "cookieValue", time() + 600, '/');

    2. To delete the cookie you have to set expiration date in the past.

      setcookie("cookieName", "anyValue", time() - 1, '/');

    Your intention to set null to a cookie is unreachable, because by definition the value of a cookie is a string. It can be empty, but it cannot be undefined or null.

Comments are closed.