PHP code example of dwnload / wp-rest-api-object-cache

1. Go to this page and download the library: Download dwnload/wp-rest-api-object-cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dwnload / wp-rest-api-object-cache example snippets


use Dwnload\WpRestApi\RestApi\RestDispatch;
add_action( RestDispatch::ACTION_CACHE_SKIPPED, function( $result, \WP_REST_Server $server, \WP_REST_Request $request ) {
	// Do something here, like create a log entry using Wonolog.
}, 10, 3 );

use Dwnload\WpRestApi\WpAdmin\Admin;
add_action( Admin::ACTION_REQUEST_FLUSH_CACHE, function( $message, $type, WP_User $user ) {
	// Do something here, like create a log entry using Wonolog.
}, 10, 3 );

use Dwnload\WpRestApi\RestApi\RestDispatch;
add_filter( RestDispatch::FILTER_CACHE_HEADERS, function( array $headers ) : array {
	$headers['Cache-Control'] = 'public, max-age=3600';
	
	return $headers;
} );

use Dwnload\WpRestApi\RestApi\RestDispatch;
add_filter( RestDispatch::FILTER_CACHE_EXPIRE, function() : int {
	// https://codex.wordpress.org/Transients_API#Using_Time_Constants
	return ( HOUR_IN_SECONDS * 5 );
} );

use Dwnload\WpRestApi\WpAdmin\Admin;
add_filter( Admin::FILTER_CACHE_OPTIONS, function( array $options ) : array {
	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;
} );

use Dwnload\WpRestApi\RestApi\RestDispatch;
add_filter( RestDispatch::FILTER_CACHE_VALIDATE_AUTH, function( bool $auth, WP_REST_Request $request ) : bool {
	// If you are running the Basic Auth plugin.
	if ( $GLOBALS['wp_json_basic_auth_error'] === true ) {
        $authorized = true;
    }
    // Otherwise, maybe do some additional logic on the request for current user...

    return $authorized;
}, 10, 2 );

use Dwnload\WpRestApi\RestApi\RestDispatch;
add_filter( RestDispatch::FILTER_CACHE_SKIP, function( bool $skip, string $request_uri ) : bool {
	if ( ! $skip && stripos( 'wp-json/dwnload/v2', $request_uri ) !== false ) {
		return true;
	}

	return $skip;
}, 10, 2 );

use Dwnload\WpRestApi\RestApi\RestDispatch;
add_action( 'save_post', function( $post_id ) {
  if ( class_exists( RestDispatch::class ) ) {
    call_user_func( [ ( WpRestApiCache::getRestDispatch(), 'wpCacheFlush' ] );
  }
} );

add_action( 'transition_post_status', function(  string $new_status, string $old_status, \WP_Post $post ) {
  if ( 'publish' === $new_status || 'publish' === $old_status ) {
    \wp_cache_flush();
  }
}, 99, 3 );