WordPress JSON data using Transients API

Set a key and an expiration time:

1
2
3
    $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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 '<p>' . $object->introduction . '</p>';
    }
}

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
$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 '<p>' . wp_kses_post( $object->introduction ) . '</p>';
    }
}
原文链接:https://xiaohost.com/3720.html,转载请注明出处。
0

评论0

请先