I would like to identify admin users and non-admin (but logged in) users through cookies. I need this feature because I use Hyper Cache (which uses cookies to identify those who send pages in cache): I would like to serve cached page to all users not logged in and to all users logged in but non-admin. The logged in admin users will not get cached pages.
2 Answers
You can use current_user_can()
to detect what type of user is logged in, if any, then use setcookie()
and $_COOKIE
to test and set the necessary cookies.
function wpse_74742_stop_cache_cookie() {
if (current_user_can('admin')) {
if (empty($_COOKIE['disable_cache'])) {
setcookie('disable_cache', 1);
}
}
}
add_action('init', 'wpse_74742_stop_cache_cookie');
This is an extremely basic example. There are a lot of details to cookie management so you may want to do a bit of reading up on cookie paths, domains and expiration.
You also may do better to simply set the cookie with the appropriate hook instead of relying on the user capabilities with the admin_init
action:
function wpse_74742_disable_admin_cache() {
if (empty($_COOKIE['disable_cache'])) {
setcookie('disable_cache', 1);
}
}
add_action('admin_init', 'wpse_74742_disable_admin_cache');