When to use transients, when not to?

I’m using WordPress and developed some site-specific plugins for it, additionally my theme is customized to fit the requirements of the plugins in the backend.

The last days I fiddled with transients in WordPress. In some tutorials they’re saying “If your’re using custom queries and their results are cachable: Use a transient“. Sounds good but I’m wondering when to use transients to get a real advantage.
I mean, even when using transients there have to be at least two queries in the background, haven’t it? The first one for checking the validity, second one for the transient itself.

Read More

So is it really useful to use a transient i.e. for a custom WP_Query?
Thanks a lot for your help and thoughts.

Related posts

Leave a Reply

1 comment

  1. Seems fairly straightforward. It’s a literal class helper that allows you to store objects in a ‘memcache’ type fashion. You first set the transient

    function do_something_here($callback_param = 'value'){
      $key = 'do_something_' . $callback_param;//set the name of our transient equal to the value of the callback param being passed in the function.
      $my_query = get_transient($myKey);  //if we've stored this request before, then use it.
      if($my_query !=== false){
        //we found a previous existing version of this query. let's use it.
        return $my_query;
      }else{
        //it doesn't exist, we need to build the transient.
        //do our database querying here, global $wpdb; etc
        //We are going to pretend our returned variable is 'george'
        $value = george;
        $length = 60*60*24; //how long do we want the transient to exist? 1 day here.
        set_transient($key, $value, $length);
        return $value;
      }
    }
    

    Now that we have created our trigger and bound it to the name of ‘$key’, we can access it anytime by using the exact value that key implies (which we declared earlier).

    echo 'I wanted to do something, so : ' . do_something('value') . ' is what i did! ';
    

    By utilizing this format you can hold queries in a ‘cache’ like world and use them to generate your responses. This is similar in a way to using ‘trigger’ events in MySql. Infact, this is a PORTION of a TECHNIQUE commonly referred to as long polling.