wp_suspend_cache_addition()WP 3.3.0

Temporarily suspends the addition of objects to the object cache.

The function allows you to disable object caching, which is used throughout WordPress. However, existing data in the cache is not deleted and can be accessed as usual.

It may be useful when importing large arrays of data to avoid consuming memory during the processing of a one-time script.

Cache suspension works only for the current request (for the duration of the current page generation).

If you need to do something else in PHP after the script, don't forget to call the function again without parameters wp_suspend_cache_addition(), to enable object caching after it has been disabled. Without object cache, WordPress performance significantly decreases.

Also see the useful function for importing large data:

No Hooks.

Returns

true|false. The current status of cache suspension.

Usage

wp_suspend_cache_addition( $suspend );
$suspend(true/false)
  • truewill stop the addition of objects to the cache.
  • falsewill enable caching.

Default: null

Examples

0

#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
0

#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() code WP 6.9.1

function wp_suspend_cache_addition( $suspend = null ) {
	static $_suspend = false;

	if ( is_bool( $suspend ) ) {
		$_suspend = $suspend;
	}

	return $_suspend;
}