0

I have a gutenberg dynamic block that makes a request to an external api to return certain data to be rendered on the front. However, there are posts that have more than 15 blocks, that is, there are 15 requests and consequently this slows down the site. Is there any way to optimize this request?

Below is the function today that returns the data

Function

function requestApi() {
        $arguments = [
            'method' => 'GET',
        ];

        $request = wp_remote_get( 'https://example.com.br/api/endpoint/product-id', $arguments );
        if (is_wp_error($request)) {
            $error_message = $request->get_error_message();
            echo "Error {$error_message}";
        }

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

        return $values;
    }

1 Answer 1

1

You could use transients:

function requestApi() {
    $cache_key = 'your_transient_name';
    $values = get_transient( $cache_key );

    // if no data in the cache
    if ( $values === false ) {

        // build the URL for wp_remote_get() function
        $arguments = [
            'method' => 'GET',
        ];
        $request = wp_remote_get( 'https://example.com.br/api/endpoint/product-id', $arguments );
        
        if ( !is_wp_error( $request ) && wp_remote_retrieve_response_code( $request ) == 200 ) {
            $values = json_decode( wp_remote_retrieve_body( $request ) );
            // print_r( $values ); // use it to see all the returned values!

            set_transient( $cache_key, $values, 7200 ); // 2 hours cache
        } else {
            return; // you can use print_r( $values ); here for debugging
        }
        
    }
    return $values;
}

With this solution, the remote query is cached via the transients, which are stored in the wp_options, and re-requested at arbitrary time intervals.

This saves you valuable resources.

The principle is described here a little more in detail:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.