The nocache_headers() function is a WordPress PHP function that sets the headers to prevent caching for different browsers. This ensures that your content is always fresh and up-to-date for your users.
Usage
nocache_headers();
Parameters
- None
Examples
Prevent caching on a custom login page
function my_custom_login_page_nocache() { nocache_headers(); } add_action('login_init', 'my_custom_login_page_nocache');
This code prevents caching on a custom login page by attaching the nocache_headers()
function to the login_init
action.
Disable caching on a specific page template
function disable_caching_on_template() { if (is_page_template('page-nocache.php')) { nocache_headers(); } } add_action('template_redirect', 'disable_caching_on_template');
This code checks if the current page uses the page-nocache.php
template, and if so, prevents caching using the nocache_headers()
function.
Prevent caching on a custom admin page
function admin_nocache_headers() { if (isset($_GET['page']) && $_GET['page'] == 'my_custom_admin_page') { nocache_headers(); } } add_action('admin_init', 'admin_nocache_headers');
This code prevents caching on a custom admin page by calling the nocache_headers()
function when the page query variable matches ‘my_custom_admin_page’.
Disable caching on all single posts
function single_post_nocache_headers() { if (is_single()) { nocache_headers(); } } add_action('template_redirect', 'single_post_nocache_headers');
This code checks if the current page is a single post, and if so, prevents caching by calling the nocache_headers()
function.
Prevent caching for a custom post type
function custom_post_type_nocache_headers() { if (is_singular('my_custom_post_type')) { nocache_headers(); } } add_action('template_redirect', 'custom_post_type_nocache_headers');
This code checks if the current page is a singular view of the ‘my_custom_post_type’ post type, and if so, prevents caching by calling the nocache_headers()
function.