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: null
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
Consider the case where stopping object caching solves the problem of memory overflow, and this happens very often when importing data into WP.
Let's say we're importing a large data set into WordPress. For example, we need to populate a table of posts from another database, or a CSV file, or by API. To do this, we have code where we use the add posts function wp_insert_post() or wp_update_post(). These functions, after adding a post to the database, add the data to the cache so that you can retrieve it later without an additional query. But we don't need caching when importing, because by default the cache is written to RAM and may not be enough as a result of import.
So for the import to work as it should, we need to turn off the cache before the import and turn it on afterwards:
// memorize the current state (this is an example that you can do this too) $was_suspended = wp_suspend_cache_addition(); // disabling caching wp_suspend_cache_addition( true ); // HERE IS YOUR IMPORT CODE. Object caching doesn't work here anymore // return the previous state of the cache back 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.1.1
function wp_suspend_cache_addition( $suspend = null ) { static $_suspend = false; if ( is_bool( $suspend ) ) { $_suspend = $suspend; } return $_suspend; }