Using WordPress ‘get_site_transient()’ PHP function

The get_site_transient() WordPress PHP function retrieves the value of a site transient. If the transient does not exist, does not have a value, or has expired, the return value will be false.

Usage

$value = get_site_transient('example_transient');

In this example, the function retrieves the value of the site transient named ‘example_transient’. If it doesn’t exist or has expired, $value will be set to false.

Parameters

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

More information

See WordPress Developer Resources: get_site_transient()

Examples

Retrieve a Site Transient Value

This example retrieves the value of a site transient named ‘special_offer’.

$value = get_site_transient('special_offer');
if ($value !== false) {
    echo "Special Offer: " . $value;
} else {
    echo "No special offer available.";
}

Check if a Site Transient Exists

This example checks if a site transient named ‘maintenance_mode’ exists.

if (get_site_transient('maintenance_mode') !== false) {
    echo "Maintenance mode is active.";
} else {
    echo "Maintenance mode is not active.";
}

Retrieve and Delete a Site Transient

This example retrieves and deletes a site transient named ‘user_count’.

$user_count = get_site_transient('user_count');
if ($user_count !== false) {
    echo "User count: " . $user_count;
    delete_site_transient('user_count');
} else {
    echo "User count not available.";
}

Retrieve a Site Transient and Set a Default Value

This example retrieves a site transient named ‘theme_color’ and sets a default value if it doesn’t exist.

$theme_color = get_site_transient('theme_color');
if ($theme_color === false) {
    $theme_color = 'blue';
}
echo "Theme color: " . $theme_color;

Retrieve and Update a Site Transient

This example retrieves a site transient named ‘page_views’, increments its value by 1, and updates the site transient.

$page_views = get_site_transient('page_views');
if ($page_views !== false) {
    $page_views++;
} else {
    $page_views = 1;
}
set_site_transient('page_views', $page_views, 3600);
echo "Page views: " . $page_views;