wp_suspend_cache_addition()
Temporarily suspends cache additions. It means that you can't add new objects to the cache after using this function.
Stops more data being added to the cache (which is used everywhere in WordPress). But existing cache data will not be deleted and can be retrieved.
This is useful for actions, such as imports, when a lot of data would otherwise be almost uselessly added to the cache and take a lot of memory.
Suspension lasts for a single page load at most.
You can call this function again without parameters if you wish to re-enable cache additions after its suspension. Do not forget that the performance of WordPress significantly drops without a cache.
No Hooks.
Return
true|false
. The current suspend status.
Usage
wp_suspend_cache_addition( $suspend );
- $suspend(true|false)
- Suspends additions if true, re-enables them if false.
Default: not changing the current setting
Examples
#1 Demonstration of disabling and enabling object caching
wp_suspend_cache_addition( true ); // suspends the cache // do something wp_suspend_cache_addition( false ); // unsuspends the cache
#2 Temporary suspension of cache additions
Let's consider a case where suspending object caching resolves the memory overflow issue, which is very common when importing data into WP.
Suppose we are importing a large array of data into WordPress. For instance, we need to populate the post table from another database, CSV file, or via an API. For this purpose, we have a code where we use the post insertion function wp_insert_post() or wp_update_post(). These functions, after adding the post to the database, add the data to the cache to retrieve it later without additional queries. However, caching is not needed during import because by default, the cache is stored in the memory and it may run out as a result of import.
Therefore, to ensure the import works as intended, we need to disable the cache before the import and then re-enable it afterward:
// Remember the current state (this is an example of how it can be done) $was_suspended = wp_suspend_cache_addition(); // Disable caching wp_suspend_cache_addition( true ); // YOUR IMPORT CODE HERE. Object caching does not work here anymore. // Restore the previous cache state wp_suspend_cache_addition( $was_suspended );
Related links:
Changelog
Since 3.3.0 | Introduced. |
wp_suspend_cache_addition() wp suspend cache addition code WP 6.7.2
function wp_suspend_cache_addition( $suspend = null ) { static $_suspend = false; if ( is_bool( $suspend ) ) { $_suspend = $suspend; } return $_suspend; }