Using WordPress ‘clean_attachment_cache()’ PHP function

The clean_attachment_cache() WordPress PHP function is used to delete attachments from the cache. Optionally, it can also clean the term object cache that is associated with the attachment ID. However, this function won’t run if $_wp_suspend_cache_invalidation is not empty.


Here’s a general way to use the clean_attachment_cache() function:

clean_attachment_cache($attachment_id, $clean_terms);

In this example, $attachment_id is the ID of the attachment you want to remove from the cache, and $clean_terms is a boolean value (true/false) that indicates whether to also clean the terms cache.


  • $id (int): This is a required parameter. It represents the attachment ID in the cache to clean.
  • $clean_terms (bool): This is an optional parameter. It determines whether to clean the terms cache. The default value is false.

More information

See WordPress Developer Resources: clean_attachment_cache()


Cleaning a single attachment cache

In this example, we’ll clean the cache for the attachment with an ID of 123.


Cleaning attachment and terms cache

Here we’re not only cleaning the attachment cache but also the terms cache for the attachment with ID 456.

clean_attachment_cache(456, true);

Attempt to clean cache while cache invalidation is suspended

This demonstrates that the function will not clean the cache if $_wp_suspend_cache_invalidation is not empty.

$_wp_suspend_cache_invalidation = true;
$_wp_suspend_cache_invalidation = false;

In this case, the cache for attachment 789 will not be cleaned.

Cleaning multiple attachments cache

You can use this function in a loop to clean cache for multiple attachments.

$attachment_ids = array(101, 102, 103);
foreach ($attachment_ids as $id) {

Cleaning all attachments cache

If you want to clean the cache for all attachments, you can do so by fetching all attachment IDs and then cleaning their cache.

$all_attachments = get_posts(['post_type' => 'attachment', 'numberposts' => -1]);
foreach ($all_attachments as $attachment) {