WordPress JSON data using Transients API

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

Set a key and an expiration time:
$json_key = 'remote_retrieve_body';
$_json_expiration = 60 * 5; // 5 minutes
$key = $json_key . md5($json_key );

(I added an MD5 hash after just for more uniqueness – doesn’t really need to be there.)
Then you do an if/else to set/retrieve the transient:
if ( $data = get_transient($key) ) {
// Already in cache - do nothing
} else {
// Fresh stuff
// MORE OF YOUR CODE HERE
$data = json_decode( $body );

// IF IT IS NEW, SET THE TRANSIENT FOR NEXT TIME
set_transient($key, $data, $_json_expiration);
}
if( ! empty( $data ) ) {
foreach($data as $object) {
echo '

' . $object->introduction . '

';
}
}

or

$url = 'url of API';
// Namespace in case of collision, since transients don't support groups like object caching.
$cache_key = md5( 'remote_request|' . $url );
$request = get_transient( $cache_key );

if ( false === $request ) {
$request = wp_remote_get( $url );

if ( is_wp_error( $request ) ) {
// Cache failures for a short time, will speed up page rendering in the event of remote failure.
set_transient( $cache_key, $request, MINUTE_IN_SECONDS * 15 );
return false;
}
// Success, cache for a longer time.
set_transient( $cache_key, $request, HOUR_IN_SECONDS * 2 );
}

if ( is_wp_error( $request ) ) {
return false;
}

$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );

if ( ! empty( $data ) ) {
foreach ( $data as $object ) {
echo '

' . wp_kses_post( $object->introduction ) . '

';
}
}

Leave a Comment