The nocache_headers() WordPress PHP function sets the headers to prevent caching for different browsers.
Usage
nocache_headers();
Parameters
- None
More information
See WordPress Developer Resources: nocache_headers
Examples
Prevent Caching on a Custom Page
_This code snippet prevents caching on a custom page by calling the nocache_headers() function._
function my_custom_page_nocache() {
if (is_page('my-custom-page')) {
nocache_headers();
}
}
add_action('template_redirect', 'my_custom_page_nocache');
Prevent Caching on All Pages
_This code snippet prevents caching on all pages by calling the nocache_headers() function._
function no_cache_all_pages() {
nocache_headers();
}
add_action('template_redirect', 'no_cache_all_pages');
Prevent Caching for Logged-in Users
_This code snippet prevents caching for logged-in users by calling the nocache_headers() function._
function nocache_for_logged_in_users() {
if (is_user_logged_in()) {
nocache_headers();
}
}
add_action('template_redirect', 'nocache_for_logged_in_users');
Prevent Caching on Custom Post Type Pages
_This code snippet prevents caching on custom post type pages by calling the nocache_headers() function._
function nocache_on_custom_post_type() {
if (is_singular('my-custom-post-type')) {
nocache_headers();
}
}
add_action('template_redirect', 'nocache_on_custom_post_type');
Add Custom Headers to wp-admin Pages
_This code snippet adds custom headers to wp-admin pages using nocache_headers()._
add_filter('nocache_headers', function() {
return array(
'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0, some-custom-thing',
'Pragma' => 'no-cache',
'Expires' => gmdate('D, d M Y H:i:s \\G\\M\\T', time())
);
});