• I’m currently hooking into save_post action, and running a function to delete caches. Some of my endpoints are fetching too much data, so I want to minimize actual users hitting those endpoints when uncached. What I want to do, is to programmatically regenerate API cache immediately after cache is deleted. I tried to do this by running the wp_remote_get function to the same endpoint, but it’s not triggering cache generation. Is there a way to do this?

    My current sample code below:

    <?php
    
    /**
     * Extending wp-rest-cache to include custom endpoints
     * and refresh cache on custom endpoints
     */
    
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
    if (is_plugin_active('wp-rest-cache/wp-rest-cache.php')) {
    
        include_once ABSPATH . 'wp-content/mu-plugins/wp-rest-cache.php';
    
    
        function wprc_add_acf_posts_endpoint($allowed_endpoints)
        {
            if (!isset($allowed_endpoints['custom/v1']) || !in_array('all-courses', $allowed_endpoints['custom/v1'])) {
                $allowed_endpoints['custom/v1'][] = 'all-posts';
            }
    
            return $allowed_endpoints;
        }
        add_filter('wp_rest_cache/allowed_endpoints', 'wprc_add_acf_posts_endpoint', 10, 1);
    
        function refreshCache($postId)
        {
            // If this is just a post revision, do nothing.
            if (wp_is_post_revision($postId) || wp_is_post_autosave($postId)) {
                return;
            }
    
            // Verify if this isn't an auto-save routine.
            // If it is that our form has not been submitted then we dont want to do anything.
            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
                return;
            }
    
            $post_type = get_post_type($postId);
    
            $caching = \WP_Rest_Cache_Plugin\Includes\Caching\Caching::get_instance();
            switch ($post_type) {
                case 'post':
                    // Fetch the categories of the post
                    $categories = wp_get_post_categories($postId, array('fields' => 'slugs'));
    
                    // Loop through each category and delete cache for its API endpoint
                    foreach ($categories as $category_slug) {
                        $endpoint = "/wp-json/wp/v2/categories?slug=" . $category_slug;
                        $caching->delete_cache_by_endpoint($endpoint);
    
                        // Trigger cache regeneration by making an HTTP request to the endpoint
                        $response = wp_remote_get(get_site_url() . $endpoint);
                        if (is_wp_error($response)) {
                            // Handle error if the request fails
                            error_log("Cache regeneration request failed for endpoint: " . $endpoint);
                        }
                    }
    
                    $caching->delete_cache_by_endpoint("/wp-json/custom/v1/all-posts");
                    break;
            }
        }
    
        add_action('save_post', 'refreshCache', 1);
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Richard Korthuis

    (@rockfire)

    Hi @geochanto

    Thank you for using our plugin!

    Did you know our plugin has an option to automatically regenerate expired and flushed caches? You can enable it by going to “Settings” > “WP REST Cache” > Tab “Settings” and check the checkbox for “Enable cache regeneration”.

    Having said that, our regenerate script also uses the wp_remote_get() function, so that should work.

    Thread Starter geochanto

    (@geochanto)

    @rockfire thank you for taking the time to respond. Yes I’m aware of the auto-regeneration feature. But as far as I can tell it’s based on a cron job.

    I’m trying to instead trigger regeneration only for specific endpoints as soon as they are cleared. This could be really powerful to avoid latency for first users who request the API endpoint right after cache has been cleared.

    However wp_remote_get seems like is not regenerating the cache after it’s cleared. There’s no X-Wp-Cached-Call when I visit the endpoint for the first time after cache clearing.

    Do you have any other pointers? Perhaps there’s a function similar to delete_cache_by_endpoint, like create_cache_by_endpoint or something.

    Plugin Author Richard Korthuis

    (@rockfire)

    @geochanto Well as said, our regeneration script is also using the wp_remote_get function, so that should work. Did you check if it actually receives the expected endpoint-output? Maybe it is receiving an error or for some reason isn’t able to reach the server (i.e. itself)?

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Programmatically regenerate cache after delete_cache_by_endpoint’ is closed to new replies.