Cache JSON responses using WordPress Transients API

Get transient; if empty, get new data.

$transient_key = 'my-transient-key'; 
$data = get_transient( $transient_key ); 

if ( false === ( $data = get_transient( $transient_key' ) ) ) { 
	$args = array(
		'post_type' => 'brand', 
		'posts_per_page' => 50,
	);
	$data = get_posts( $args );
	set_transient( $transient_key, $data, 12 * HOURS_IN_SECONDS );
}

wp_send_json_success( $data );
wp_die();

Expiration

The third parameter of set_transient is expiration in seconds.

Constants are available:

MINUTE_IN_SECONDS  = 60 (seconds)
HOUR_IN_SECONDS    = 60 * MINUTE_IN_SECONDS
DAY_IN_SECONDS     = 24 * HOUR_IN_SECONDS
WEEK_IN_SECONDS    = 7 * DAY_IN_SECONDS
YEAR_IN_SECONDS    = 365 * DAY_IN_SECONDS

Delete transient when saving

Create a hook:

add_action( 'save_post', 'delete_transient' );

Create a function to delete transients:

function delete_transient() {
	delete_transient( 'transient-key' );
}

Delete multiple transients

If a function can produce different results, transient keys must be different. So, when you need to delete its transients, all keys must be saved somewhere. Let’s save it as an option.

In the JSON request function:

$transients = get_option( 'transients', '' );
if ( '' == $transients || is_string( $transients ) ) {
	$transients = array();
}
$transients[] = $transient_key;
update_option( 'cs_transients', $transients );

The hook function:

add_action( 'save_post', 'delete_transients' );

function delete_transients() {
	$transients = get_option( 'transients' );
	if ( $transients && is_array( $transients ) ) {
		foreach ( $transients as $transient ) {
			delete_transient( $transient );
		}
	}
}

A function to set a new transient may be added, so cache is set before an user accessess the site.

References