Last active
August 5, 2019 13:53
-
-
Save danielbachhuber/5cf816d99fd973cd5832a5715576ade8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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