Cache Busting – Removing Cookie in a Cleaner way When Logout from Wordpress

The presence of  in the browser when the session is no longer valid, presents a big problem for cache solutions (clouduflare, varnish, nginx, etc). The solution is relatively simple and does not involve too much work, we just have to know which cookies are no longer useful when the session is no longer valid and consequently we eliminate them when accessing a page from the website.

In wordpress there are cases when the session is no longer valid, but some cookies remain active in the browser, in which case the cache on the server or CDN (or reverseproxy) does not work properly.

To solve this problem, which millions of sites suffer from, you have a very simple solution below. All you have to do is copy the code and add it to the functions.php file from the active theme!

function byrev_Clean_WP_NotLoggedIn() {
    if (!is_user_logged_in()) {
        if (!empty($_COOKIE)) {
            $urlparts = parse_url(site_url());
            $domain = $urlparts [host];
            foreach ($_COOKIE as $key => $val) {
                if (preg_match("/wordpress/i", $key) || preg_match("/wp/i", $key)) {
                    unset($_COOKIE[$key]);
                    setcookie($key, null, -1, '/', $domain);
                    setcookie($key, null, -1, '/');
                }
            }
            unset($_COOKIE['tk_ai']);
            setcookie('tk_ai', null, -1, '/');
        }
    }
}
byrev_Clean_WP_NotLoggedIn();

Note:

In this case, the most important cookie to delete is wordpress_logged_in_ *, the rest are less important.

Happy Coding !

byrev Written by:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *