Skip to content

Instantly share code, notes, and snippets.

@vapvarun
Created April 14, 2026 04:05
Show Gist options
  • Select an option

  • Save vapvarun/a8fd5607d5ffd9895ffca9eab98e9ca0 to your computer and use it in GitHub Desktop.

Select an option

Save vapvarun/a8fd5607d5ffd9895ffca9eab98e9ca0 to your computer and use it in GitHub Desktop.
WordPress Transients API: Cache Database Queries for Better Performance (wppioneer.com)
set_transient( 'my_cache_key', $data, HOUR_IN_SECONDS );
$cached = get_transient( 'my_cache_key' );
delete_transient( 'my_cache_key' );
set_site_transient( 'my_network_cache', $data, DAY_IN_SECONDS );
get_site_transient( 'my_network_cache' );
delete_site_transient( 'my_network_cache' );
function my_get_weather( $city ) {
$cache_key = 'weather_' . md5( $city );
$weather = get_transient( $cache_key );
if ( false === $weather ) {
$response = wp_remote_get( "https://api.weather.example/?q=$city" );
if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
$weather = json_decode( wp_remote_retrieve_body( $response ), true );
set_transient( $cache_key, $weather, 15 * MINUTE_IN_SECONDS );
} else {
// Cache the failure briefly so we do not hammer a broken API.
set_transient( $cache_key, [ 'error' => true ], MINUTE_IN_SECONDS );
return [];
}
}
return isset( $weather['error'] ) ? [] : $weather;
}
wp_cache_set( 'my_key', $data, 'my_group', 300 );
$data = wp_cache_get( 'my_key', 'my_group', false, $found );
wp transient list
wp transient get popular_posts_v1
wp transient delete popular_posts_v1
wp transient delete --all # nuclear option; useful after schema changes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment