Creating dynamic partial content in Cached WordPress Pages using Rest API

Assume that we are using Fully cached static pages by any cache plugin. But we need to server some fresh content inside some block of the page.

To understand it easier let’s consider that we have fully cached homepage where there is a block about the number of your customers.

Something like this

PAGE HEADER HERE...
PAGE CONTENT HERE...
<div class="customer_count_div">546 TRUSTED CUSTOMERS</div>
PAGE FOOTER HERE...

So, our task is to show some dynamic or transient-cached content inside that “customers” div, while the page is fully static by a cache plugin.

We will use WP REST API for that.

First we need to init that “fresh content fetcher” script which calls API.

add_action('wp_footer',function(){
    ?>
    <script>
        jQuery(document).ready(function(){
            jQuery.ajax( {
                url: "HTTPS://YOURWEBSITEURL/wp-json/app/v1/load-fresh-partial-content",
                method: 'GET',
            }).done( function ( response ) {
                if(response){
                    response=JSON.parse(response);
                    jQuery(".customer_count_div").html(response.customer_count_div);
                    //in one single API request you can change a lot of partial content, not only customer_count_div
                }
            });
    });
    </script>
    <?php
 },999);

This block will get the fresh partial content from your server backend and change the static page partial content.

Now let’s implement the API endpoint for this block.

add_action( 'rest_api_init', function () {
    register_rest_route( 'app/v1', '/load-fresh-partial-content/', array(
        'methods' => 'GET',
        'callback' => 'Guaven_load_fresh_partial_content',
        'permission_callback' => 'Guaven_wp_api_permission'
    ));
});

function Guaven_load_fresh_partial_content(){
    global $wpdb;
    $return=[];
    $return["customer_count_div"] = $wpdb->get_var("select meta_value from $wpdb->postmeta where meta_key='customer_count'");
    //or $return["customer_count_div"] = get_transient('customer_count');

    //in one single API request you can add a lot of partial content, not only customer_count_div
    $response = new WP_REST_Response($return);
	$response->set_status(200);
	return $response;
}
function Guaven_wp_api_permission(){
    //some conditions can be here
    return true;
}

What this block does is getting dynamic value of “customer count” from your database and return it as a JSON string.

As you can see from the example, you can add any amount of partial content there, using the same endpoint. If any questions, leave a comment below.

Get more useful WP tricks and snippets by subscribing to my mailclub.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.