The right way to use wordpress transient, set transient, get transient, delete transient, simple tutorial and example without complexity.

How To Use WordPress Transient

Very easy, using Transient API, we will set transient, and get transient, and delete transient, in this exmple we will get SoundCloud Track Thumbnail using WordPress HTTP API and save data in wordpress transient.

Set And Get Transient

In this function we will get SoundCloud Track Thumbnail from URL, and thumbnail link will be saved in wordpress transient:

function WPTime_get_soundcloud_thumbnail($url){ // By Qassim Hassan

    $transient_name = md5($url);
    $get_transient = get_transient( $transient_name );

    if ( empty( $get_transient ) ){ // if no data in our transient

        $client_id = "client_id"; // entre your client id.

        $get = wp_remote_get("https://api.soundcloud.com/resolve.json?url=$url&client_id=$client_id");

        $retrieve = wp_remote_retrieve_body($get);

        $result = json_decode($retrieve, true);

        $image = str_replace("large.jpg", "t300x300.jpg", $result['artwork_url']); // output

        $cache_time = 3600 * 24; // cache time: 3600 * 24 = 24 hours (1 day), 3600 = 1 hour, enter 3600 if you want 1 hour only, 3600 * 2 = 2 hours, etc.

        set_transient($transient_name, $image, $cache_time);

        return $image;

    }

    else{ // if has data in our transient
        return $get_transient;
    }

}

Register SoundCloud App and get client ID.

Usage:

echo WPTime_get_soundcloud_thumbnail("https://soundcloud.com/fatma-gazzar/idiaad4foqia");

Now you will get thumbnail and thumbnail link will be saved in wordpress transient for 24 hours, because cache time is 3600 * 24, (3600 = 1 hour), (3600 * 12 = 12 hours), (3600 * 24 * 30 = 1 month).

Delete Transient

To delete transient, use this function:

delete_transient("enter_transient_name");

Enter your transient name, for example if your transient name is “hello”, enter “hello”, but in our example transient name is md5 link, so we will delete transient like this:

$transient_name = md5("https://soundcloud.com/fatma-gazzar/idiaad4foqia");

delete_transient($transient_name);

Now transient will be deleted.