[bs_button size=”md” type=”default” value=”Back to ‘WordPress Transients API'” href=”https://artiss.blog/transients/”]
At its most basic level, and for most developers, there are 3 Transient functions…
delete_transient(). These do exactly what their names suggest – they create a new transient (or overwrite an existing one), fetch a transient and delete a transient. Let’s look at each in turn…
This is the most difficult of the transient functions to use (and that’s not saying much), as it has 3 parameters (the last of which is optional)…
- Transient name – the name you wish to give the transient.
- Transient value – the value you wish to store.
- Expiry – when you wish the transient to expire. This is given as the time until expiration in seconds from now. The default is 0, which means it never expires.
The function returns either true or false, depending on whether the transient was successfully stored or not.
$transient_rc = set_transient( 'test_transient', 'Hello World', 86400 );
This would save our transient for one day before expiring and return the success (or otherwise) of this into the variable
Now you’ve saved a transient, you want to retrieve it and this one needs just one parameter – the transient name. In return, the transient value is retrieved, or false is no transient was found.
However, be aware of the following…
This should be checked using the identity operator ( === ) instead of the normal equality operator, because an integer value of zero (or other “empty” data) could be the data you’re wanting to store. Because of this “false” value, transients should not be used to hold plain boolean values. Put them into an array or convert them to integers instead.WordPress Codex
get_transient, this requires just the one parameter, the transient name. True or false is returned, depending on the success of the transient removal.
You didn’t think it would be that easy, did you? For those running a multisite installation of WordPress, there are also site functions to consider.
If you’re using multisite, all of the above functions relate to individual blogs – i.e. the transient is stored and only accessible to the specific blog that the code is running for. Site functions allows you to store, retrieve and delete transients that will affect all the blogs within the multisite installation.
The functions work exactly the same but are named differently –
So, a transient saved with
set_site_transient() can be fetched, via
get_site_transient(), no matter which blog of the installation it is.
And that is the transient API! How easy is that to use?