Zack Saadioui
1/29/2025
1
wp_remote_get()1
wp_remote_get()1 2 3 4 5$response = wp_remote_get( 'https://api.example.com/data' ); if ( is_wp_error( $response ) ) { return 'Failed to retrieve data.'; } $data = json_decode( wp_remote_retrieve_body( $response ));
1 2 3 4 5 6 7 8$transient_key = 'api_data_key'; $data = get_transient( $transient_key ); if ( false === $data ) { // No transient found, make API request. $response = wp_remote_get( 'https://api.example.com/data' ); $data = json_decode( wp_remote_retrieve_body( $response )); set_transient( $transient_key, $data, HOUR_IN_SECONDS ); // Cache for 1 hour. }
1
wp_ajax1
2
3
4
5
php
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_script( 'my-ajax-script', get_template_directory_uri() . '/js/my-ajax.js', array( 'jquery' ), null, true );
    wp_localize_script( 'my-ajax-script', 'my_ajax_object', [ 'ajax_url' => admin_url( 'admin-ajax.php' ) ] );
} );1
2
3
4
5
6
7
8
9
php
add_action( 'wp_ajax_fetch_data', 'fetch_data_callback' );
add_action( 'wp_ajax_nopriv_fetch_data', 'fetch_data_callback' ); // Allow public access.
function fetch_data_callback() {
    $response = wp_remote_get( 'https://api.example.com/data' );
    $data = json_decode( wp_remote_retrieve_body( $response ));
    echo json_encode( $data );
    wp_die(); // this is required to terminate immediately and return a proper response
}1
2
3
4
5
6
7
8
9
10
11
12
13
javascript
jQuery(document).ready(function($) {
    $('#fetch-button').click(function() {
        $.ajax({
            url: my_ajax_object.ajax_url,
            type: 'POST',
            data: {action: 'fetch_data'},
            success: function(response) {
                // handle the response data here
            }
        });
    });
});1
Promises1
Promise.all()1
2
3
4
5
6
7
8
javascript
Promise.all([
    fetch('https://api.example.com/data1'),
    fetch('https://api.example.com/data2')
]).then(responses => Promise.all(responses.map(res => res.json())))
.then(data => {
    // Do something with your data
});1
2
3
4
5
6
7
8
php
$cache_key = 'api_response_key';
$data = wp_cache_get( $cache_key );
if ( false === $data ) {
    // Cache miss; make API call.
    $data = some_function_to_get_api_data();
    wp_cache_set( $cache_key, $data, '', 3600 ); // Cache for an hour
}1
rest_prepare_post1
2
3
4
5
6
php
add_filter( 'rest_prepare_post', 'modify_post_response', 10, 3 );
function modify_post_response( $response, $post, $request ) {
    $response->data['custom_field'] = 'value'; // Add a custom field
    return $response;
}1
wp_remote_get()Copyright © Arsturn 2025