airesvsg/wp-rest-api-cache

Enable caching for WordPress REST API and increase speed of your application.

Installs: 391

Dependents: 0

Suggesters: 0

Security: 0

Stars: 248

Watchers: 10

Forks: 37

Open Issues: 10

Type:wordpress-plugin

dev-master 2019-02-28 13:02 UTC

This package is auto-updated.

Last update: 2024-09-12 06:09:12 UTC


README

Enable caching for WordPress REST API and increase speed of your application

Installation

  1. Copy the wp-rest-api-cache folder into your wp-content/plugins folder
  2. Activate the WP REST API Cache plugin via the plugin admin page

Filters

How to use filters

  • sending headers
add_filter( 'rest_cache_headers', function( $headers ) {
	$headers['Cache-Control'] = 'public, max-age=3600';
	
	return $headers;
} );
  • changing the cache timeout
add_filter( 'rest_cache_timeout', function() {
	// https://codex.wordpress.org/Transients_API#Using_Time_Constants
	return 15 * DAY_IN_SECONDS;
} );

or

add_filter( 'rest_cache_get_options', function( $options ) {
	if ( ! isset( $options['timeout'] ) ) {
		$options['timeout'] = array();
	}

	// https://codex.wordpress.org/Transients_API#Using_Time_Constants
	$options['timeout']['length'] = 15;
	$options['timeout']['period'] = DAY_IN_SECONDS;
	
	return $options;
} );
  • skipping cache
add_filter( 'rest_cache_skip', function( $skip, $request_uri ) {
	if ( ! $skip && false !== stripos( $request_uri, 'wp-json/acf/v2' ) ) {
		return true;
	}

	return $skip;
}, 10, 2 );
  • show / hide admin links

WP REST API Cache

  • empty cache on post-save

You can use the wordpress default filter "save_post" if you like to empty the cache on every save of a post, page or custom post type.

add_action( 'save_post', function( $post_id ) {
  if ( class_exists( 'WP_REST_Cache' ) ) {
    WP_REST_Cache::empty_cache();
  }
} );