Setting Cookies in WordPress

How to set cookies in more flexible way?

When you need to set cookie in WordPress project rather than using a hard-coded path and domain variables use COOKIEPATH and COOKIE_DOMAIN constants provided by default by WordPress in wp-config.php.

setcookie('notice_closed', '1', time() + HOUR_IN_SECOND, COOKIEPATH, COOKIE_DOMAIN);

Thanks to this you'll get the code that is more flexible and prepared to change. If there will be need to change those values, you'll be able to do it in one place without reviewing other ones. It also helped me solve provlems of setting cookies in WP AJAX actions.

Feedback

How satisfied you are after reading this article?