I am trying to use the w3tc_cache_get() function to get cached data in WordPress. However, I am getting the error message "Call to undefined function w3tc_cache_get()".
I have checked the following:
- The W3 Total Cache plugin is activated and the caching feature is enabled.
- The w3tc_cache_get() function is inside a specific file which I included in my theme's functions.php file using "require" method.
- The version of WordPress I am using is 6.2.2.
- The version of the W3 Total Cache plugin I am using is the latest version.
<?php
// Set the expiration time for the cached data.
define('WP_ROCKET_CACHE_EXPIRY', 60 * 60);
// Enable caching for dynamic content.
add_filter('w3tc_cache_dynamic', '__return_true');
// Function to fetch data from an API.
function fetch_api_data($api_url) {
$api_response = wp_remote_get($api_url);
if (wp_remote_retrieve_response_code($api_response) === 200) {
return json_decode(wp_remote_retrieve_body($api_response));
} else {
return array();
}
}
function cache_api_data($api_url, $data) {
$cache_key = 'api_data_' . $api_url;
w3tc_cache_set($cache_key, $data, 'default', W3TC_CACHE_EXPIRY);
}
function get_cached_data ($api_url) {
$cache_key = 'api_data_'.$api_url;
$cached_data = w3tc_cache_get($cache_key, 'default');
if ($cached_data !== null) return $cached_data;
return [];
}
function get_api_data ($api_url = "localhost/api/v1/temp_name") {
$cached_data = get_cached_data ($api_url);
if ( !empty($cached_data) ) return $cached_data;
$api_response = fetch_api_data ($api_url);
cache_api_data ($api_url, $api_response);
return $api_response;
}
Basically, I want to get data from an API and store it in the cache. This way, whenever I need to get data from the API, I can call the get_api_data() function, which will check if the data is already cached. If the data is cached, the function will return the cached data. If the data is not cached, the function will fetch the data from the API and store it in the cache.