Using WordPress ‘clean_blog_cache()’ PHP function

The clean_blog_cache() WordPress PHP function is used to clean the blog cache. This function specifically targets the site object or ID which is needed to be cleared from the cache.

Usage

Let’s consider an example. Suppose you have a blog with the ID ‘5’. You want to clean its cache. You can use the clean_blog_cache() function as shown below:

clean_blog_cache(5);

This will clear the cache of the blog with the ID ‘5’.

Parameters

  • $blog (WP_Site|int): This is a required parameter. It represents the site object or the ID of the site that needs to be cleared from the cache.

More information

See WordPress Developer Resources: clean_blog_cache()

Examples

Clearing Cache of Blog by ID

If you want to clear the cache of a blog and you know its ID, just use the clean_blog_cache() function with the blog ID as parameter.

// Define the blog ID
$blog_id = 10;

// Clear the cache of the blog with the defined ID
clean_blog_cache($blog_id);

Clearing Cache of Multiple Blogs

In case you want to clear the cache of multiple blogs, you can use a loop.

// Define the blog IDs
$blog_ids = array(1, 2, 3, 4, 5);

// Loop through the array and clear cache of each blog
foreach($blog_ids as $blog_id) {
    clean_blog_cache($blog_id);
}

Clearing Cache of Current Blog

To clear the cache of the current blog, you can use the function get_current_blog_id() to get the current blog ID.

// Get current blog ID
$current_blog_id = get_current_blog_id();

// Clear the cache of the current blog
clean_blog_cache($current_blog_id);

Clearing Cache of Blog with WP_Site Object

You can also use a WP_Site object to clear the cache.

// Get a WP_Site object
$blog_site = get_site(1);

// Clear the cache of the blog with the WP_Site object
clean_blog_cache($blog_site);

Clearing Cache when Blog Post is Updated

You can clear the cache of a blog when a post is updated. For this, you can use the action hook save_post.

// Function to clear cache when post is updated
function clear_cache_on_update($post_id) {
    // Get the blog ID from the post
    $blog_id = get_post_field('blog_id', $post_id);

    // Clear the cache of the blog
    clean_blog_cache($blog_id);
}

// Hook the function to 'save_post' action
add_action('save_post', 'clear_cache_on_update');

In this code, when a post is updated, the function clear_cache_on_update() is called. This function gets the blog ID from the post and clears its cache.