Chandra Patel

Just Another Developer

wp_cache_flush() – Think twice before using it

wp_cache_flush() is WordPress core function which can be used to flush entire object cache. But why I said, “Think twice before using it“. There is a reason why not to use this function in the plugin/theme.

Many sites heavily rely on and use object cache to improve the site performance. If any plugin calls wp_cache_flush() then it will clear entire object cache of the site. This is likely to cause performance issues because data will need to be fetched from the database and then it will be stored in the object cache freshly.

Recently I came across one plugin which stored some of its query results in the object cache. Cache key was generated using query params. As the cache key was dynamic, the plugin was not having any logic to flush the cache only specific to their code. Instead, they used wp_cache_flush() to clear the cache. However, it would flush entire site’s object cache. Why forcefully flush entire object cache? Just because they have not had a static cache key to flush their plugin specific cache?

It is better to think of alternatives where only plugin specific cache flush logic can be written. For example,

  1. One can keep lesser expiry time for its cache key.
  2. Add new cache key which saves timestamp when your content has been updated. You can use that timestamp in your functions where you can take the difference between the content updated timestamp and current timestamp and if the difference is more than cache expiry duration then get the latest content from the database and set in the cache. Also, delete that cache which saves the timestamp.
  3. You can store all the dynamic cache keys in the serialized array as an option. Then on content update get those cache keys from option and then delete it.

In WordPress, there is no way to delete/clear the cache by the group. There are valid reasons why this mechanism is not available and the details can be tracked here: https://core.trac.wordpress.org/ticket/4476

Tldr; wp_cache_flush() should only be used when you want to flush entire website’s object cache and you know what you are doing 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.