I want to store some Twitter API data in WordPress. After every hour, I want to fetch new data from Twitter, and update only if the data is successfully retrieved from API (sometimes the API gives error, so in that case I want to keep using the old data).
So in that case should I use set_transient
or update_option
?
If I used update_option
then at least I can check if new data is available before updating the option.
What happens if I set_transient
for an hour and after one hour the new data is not available, will I lose the stored data?
A transient is not like a
wp_cron
job in that they don’t update themselves when a set time has elapsed. A transient will update when an attempt is made to access the data. If you actually do need an approximately hourly update you will need to usewp_cron
, though in practice it may not matter much and you could use awp_cron
job to update the transient if you wanted.But to answer the question asked, when you run
get_transient
to check your transient value it will returnfalse
if “the transient does not exist, does not have a value, or has expired”, but you don’t know which, and runningget_transient
also runsdelete_option
if the timeout has expired. I verified that the transient is in fact deleted from the database by setting up a 60 second timeout test, and checking the database itself for the transient.Transients do have an advantage over normal options in terms of caching.
This may not matter on your site in particular, but in general it does count toward using the Transients API. You will have to do something about the lost data issue, though. Something like…