Transients store data temporarily in the database or in the object cache, with an expiration time. They are perfect for saving the result of slow work, like an external API request or a heavy query, so it does not run on every page load.

The basic pattern

function lotgrafix_get_remote_data() {
    $data = get_transient( 'lotgrafix_remote_data' );

    if ( false === $data ) {
        $response = wp_remote_get( 'https://api.example.com/data' );

        if ( is_wp_error( $response ) ) {
            return array();
        }

        $data = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( is_array( $data ) ) {
            set_transient( 'lotgrafix_remote_data', $data, HOUR_IN_SECONDS );
        }
    }

    return is_array( $data ) ? $data : array();
}

The three functions

  • set_transient( $name, $value, $expiration ): saves the value for a number of seconds.
  • get_transient( $name ): returns the value, or false if it expired or does not exist.
  • delete_transient( $name ): removes it immediately.

Time constants

  • MINUTE_IN_SECONDS
  • HOUR_IN_SECONDS
  • DAY_IN_SECONDS
  • WEEK_IN_SECONDS

Clear the cache when content changes

function lotgrafix_clear_cache() {
    delete_transient( 'lotgrafix_remote_data' );
    delete_transient( 'lotgrafix_popular_posts' );
}
add_action( 'save_post', 'lotgrafix_clear_cache' );

Cache the result of a heavy query

$lotgrafix_ids = get_transient( 'lotgrafix_popular_posts' );

if ( false === $lotgrafix_ids ) {
    $lotgrafix_ids = get_posts( array(
        'numberposts' => 5,
        'orderby'     => 'comment_count',
        'fields'      => 'ids',
    ) );
    set_transient( 'lotgrafix_popular_posts', $lotgrafix_ids, 6 * HOUR_IN_SECONDS );
}

Notes

  • The transient name can have a maximum of 172 characters.
  • With a persistent object cache like Redis, transients live in memory and may disappear earlier than expected, so your code must always handle false.
  • Never store sensitive data in transients.
«
»