WordPress at a glance

wp_suspend_cache_addition() WP 3.3.0

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 Basic usage

wp_suspend_cache_addition( true ); // suspends the cache

// do something

wp_suspend_cache_addition( false ); // unsuspends the cache

#2 Temporary suspension of cache additions

Suppose that we need to import a large file that contains posts data, and add these posts to the site with wp_insert_post(). The wp_insert_post() caches all the posts that were added with it to make the further posts retrieval less resource-intensive. But in our case, we don't need that; and the memory of the server (it's where the cache resides) just may not be enough to fit all the posts from this large file there, and you will get an error.

So to make the import work properly, we can suspend the cache before the import and unsuspend it after:

// suspends the cache
wp_suspend_cache_addition( true );

// here is the import code...
// and new data will not be added to the cache at all...

// unsuspends the cache
wp_suspend_cache_addition( false );

Notes

  • Static. true/false. $_suspend

Changelog

Since 3.3.0 Introduced.

Code of wp suspend cache addition: wp-includes/functions.php WP 5.2.2

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

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

	return $_suspend;
}

Related Functions

From tag: cache (caching)

No comments
    Hello, !     Log In . Register