Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Filters wp_remote_get() to:
* 1. Return a value from the cache when it's available.
* 2. Write a value to the cache when it's been fetched.
*
* Requires the WP_IMPORT_CACHE constant to be set to a writable directory.
*/
if ( defined( 'WP_CLI' ) && WP_CLI ) {
add_filter(
'pre_http_request',
function( $retval, $r, $url ) {
// Only run when importing.
if ( ! defined( 'WP_IMPORTING' ) || ! WP_IMPORTING
|| ! defined( 'WP_IMPORT_CACHE' ) ) {
return $retval;
}
$key = md5( $url );
$cache_path = trailingslashit( WP_IMPORT_CACHE ) . $key;
if ( file_exists( $cache_path ) ) {
WP_CLI::log( " - Importing {$url} from cache..." );
copy( $cache_path, $r['filename'] );
return array(
'headers' => array(),
'response' => array(
'code' => 200,
'message' => 'OK',
),
'cookies' => array(),
'filename' => $r['filename'],
);
}
return $retval;
},
10,
3
);
add_filter(
'http_response',
function( $response, $args, $url ) {
// Only run when importing.
if ( ! defined( 'WP_IMPORTING' ) || ! WP_IMPORTING
|| ! defined( 'WP_IMPORT_CACHE' ) ) {
return $response;
}
if ( 200 !== wp_remote_retrieve_response_code( $response )
|| empty( $response['filename'] ) ) {
return $response;
}
if ( ! is_dir( WP_IMPORT_CACHE ) ) {
@mkdir( WP_IMPORT_CACHE );
}
WP_CLI::log( " - Saving {$url} to cache..." );
$key = md5( $url );
$cache_path = trailingslashit( WP_IMPORT_CACHE ) . $key;
file_put_contents( $cache_path, file_get_contents( $response['filename'] ) );
return $response;
},
10,
3
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.