Should I use set_transient or update_option?

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.

Read More

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?

Related posts

Leave a Reply

1 comment

  1. 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 use wp_cron, though in practice it may not matter much and you could use a wp_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 return false if “the transient does not exist, does not have a value, or has expired”, but you don’t know which, and running get_transient also runs delete_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.

    Also of note is that Transients are inherently sped up by caching
    plugins, where normal Options are not. A memcached plugin, for
    example, would make WordPress store transient values in fast memory
    instead of in the database. For this reason, transients should be used
    to store any data that is expected to expire, or which can expire at
    any time.

    http://codex.wordpress.org/Transients_API

    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…

    function get_twit_wpse_94911() {
      $trans = 'test_transient';
      $data = get_option('_transient_'.$trans);
      if (empty($data)) {
        $data = 'Yay Awesome Data'; // default data if you want it
      }
      if (!get_transient($trans)) {
        // check for new information
        // $new = fetch_twitter_however_you_are_doing_it();
        // check for the integrity of the new data
        // !empty() may not be adequate
        if (!empty($new)) {
          $data = $new;
        }
        set_transient($trans,$data,60*60);
      }
      return get_transient($trans);
    }