Programmatically regenerate cache after delete_cache_by_endpoint
-
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)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘Programmatically regenerate cache after delete_cache_by_endpoint’ is closed to new replies.