Setting a Custom Cookie in WordPress only for Logged In Customer/User (non-admin)

There are a few things going on there that need to be tweaked. The code below should do what you need.

  • The setting of the cookie shouldn’t query for is the user logged-in. This can’t be relied upon to return true on a login request. Just rely on the wp_login hook to assure you that the user is logging in.
  • I’ve set this with a long cookie lifetime – i.e 1 week. using the WordPress constant WEEK_IN_SECONDS. You can change this by replacing WEEK_IN_SECONDS with a number (of seconds) you want it to last.
  • The deletion of the cookie is done by setting a low/negative value so that it’s essentially “expired”
  • Important: Make sure this is added to your functions.php or anywhere you can be sure it will be executed in-time before a login request is processed.
add_action( 'wp_login', 'add_custom_cookie' );
function add_custom_cookie() {
    setcookie( 'cookie_name', 'cookie value', time()+WEEK_IN_SECONDS );
}

// To Remove Cookie
add_action( 'wp_logout', 'remove_custom_cookie' );
function remove_custom_cookie() {
    setcookie( 'cookie_name', '', -1000000 );
}

tech