最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Cache WP remote_get HTTP Response using Transients

programmeradmin3浏览0评论

Using wp_remote_get keeps pinging the API on every page load. Which increase the server resource.

Is it possible to cache the response of the API store it using Transients and use it for next 5 minutes instead of keep pinging everytime?

And After 5 Minutes it should send request again and rewrite the stored value.

Here is my code for API Request. How to do this? I'm new to this. Help me please

function display_api_response() {
    $api_url = ";;
$response = wp_remote_get($api_url);
   if ( 200 === wp_remote_retrieve_response_code($response) ) {
        $body = wp_remote_retrieve_body($response);

        if ( 'a' === $body ) {
          echo 'A wins';
        }else {
          // Do something else.
        }
   }
}
add_action( 'init', 'display_api_response' );

Using wp_remote_get keeps pinging the API on every page load. Which increase the server resource.

Is it possible to cache the response of the API store it using Transients and use it for next 5 minutes instead of keep pinging everytime?

And After 5 Minutes it should send request again and rewrite the stored value.

Here is my code for API Request. How to do this? I'm new to this. Help me please

function display_api_response() {
    $api_url = "https://randletter2020.herokuapp";
$response = wp_remote_get($api_url);
   if ( 200 === wp_remote_retrieve_response_code($response) ) {
        $body = wp_remote_retrieve_body($response);

        if ( 'a' === $body ) {
          echo 'A wins';
        }else {
          // Do something else.
        }
   }
}
add_action( 'init', 'display_api_response' );
Share Improve this question asked Oct 12, 2020 at 18:38 Ava JuanAva Juan 152 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 1
function display_api_response() {
    $body = get_transient( 'my_remote_response_value' );
    
    if ( false === $body ) {
        $api_url = "https://randletter2020.herokuapp";
        $response = wp_remote_get($api_url);
    
        if (200 !== wp_remote_retrieve_response_code($response)) {
            return;
        }
    
        $body = wp_remote_retrieve_body($response);
        set_transient( 'my_remote_response_value', $body, 5*MINUTE_IN_SECONDS );
    }

    if ('a' === $body) {
        echo 'A wins';
    } else {
        // Do something else.
    }
}
add_action('init', 'display_api_response');

At first, the transient doesn't exist, so we send a request and save the $body as a transient value. Next time, if the transient exists, we skip sending request.

Check the Transient Handbook for more information.

发布评论

评论列表(0)

  1. 暂无评论