Using WordPress ‘get_transient()’ PHP function

The get_transient() WordPress PHP function retrieves the value of a transient.

Usage

$result = get_transient('example_transient');

Parameters

  • $transient (string): Required. Transient name. Expected to not be SQL-escaped.

More information

See WordPress Developer Resources: get_transient()

Examples

Retrieve a transient value

This example retrieves the value of a transient named ‘special_query_results’ and stores it in the $special_query_results variable.

$special_query_results = get_transient('special_query_results');

Cache query results using transients

This example checks if the transient ‘special_query_results’ exists and has a valid value. If not, it runs a new query and stores the results in the transient.

if (false === ($special_query_results = get_transient('special_query_results'))) {
    $special_query_results = new WP_Query('cat=5&order=random&tag=tech&post_meta_key=thumbnail');
    set_transient('special_query_results', $special_query_results);
}

Delete expired transients

This note explains that when using get_transient() on an expired transient, it will be deleted. Non-expired transients or transients without expiration will only be deleted with delete_transient().

Force live data during development

This example shows how to use WP_DEBUG to always retrieve live data during the development stage.

if (WP_DEBUG || false === ($special_query_results = get_transient('special_query_results'))) {
    $special_query_results = new WP_Query('cat=5&order=random&tag=tech&post_meta_key=thumbnail');
    set_transient('special_query_results', $special_query_results);
}

Retrieve and display transient data

This example retrieves the transient data and displays it if it exists, otherwise, it displays a default message.

$transient_data = get_transient('example_transient');

if (false !== $transient_data) {
    echo 'Transient data: ' . $transient_data;
} else {
    echo 'No data found.';
}