Skip to content

Instantly share code, notes, and snippets.

@LearnWebCode
Created January 31, 2025 19:44
Show Gist options
  • Save LearnWebCode/7e94e9b3009eec01a1dc22b7a889a876 to your computer and use it in GitHub Desktop.
Save LearnWebCode/7e94e9b3009eec01a1dc22b7a889a876 to your computer and use it in GitHub Desktop.
WordPress functions to fetch external JSON (and store in transient + option backup) and also functions to setup programmatic URL patterns and use custom template files for said URLs
function get_cached_external_json($url) {
$transient_key = 'our_fetched_json_' . md5($url);
$option_key = 'our_fetched_json_backup_' . md5($url);
$cached_data = get_transient($transient_key);
if (false !== $cached_data) {
return $cached_data;
}
$response = wp_remote_get($url, array(
'timeout' => 15,
'headers' => array(
'Accept' => 'application/json'
)
));
if (is_wp_error($response)) {
// Return last known good data from options if available
$backup_data = get_option($option_key, false);
if ($backup_data) {
return $backup_data;
}
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (null === $data) {
// Return last known good data from options if available
$backup_data = get_option($option_key, false);
if ($backup_data) {
return $backup_data;
}
return false;
}
// Set transient for x amount of time, measured in seconds
set_transient($transient_key, $data, 8 * HOUR_IN_SECONDS);
// Store a persistent backup in options (with autoload disabled)
if (false === get_option($option_key, false)) {
add_option($option_key, $data, '', false);
} else {
update_option($option_key, $data, false);
}
return $data;
}
///////////////
function custom_repo_rewrite_rule() {
add_rewrite_rule('^repo/([^/]+)/?', 'index.php?custom_repo=$matches[1]', 'top');
}
add_action('init', 'custom_repo_rewrite_rule');
function custom_repo_query_vars($query_vars) {
$query_vars[] = 'custom_repo';
return $query_vars;
}
add_filter('query_vars', 'custom_repo_query_vars');
///////////////
function custom_repo_template_include($template) {
if (get_query_var('custom_repo')) {
return get_template_directory() . '/repo-template.php';
}
return $template;
}
add_filter('template_include', 'custom_repo_template_include');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment