WordPress Caching – Transients API or “update_user_meta ” Cronjob?

Although both of your options (that is, using transients or using a cron job) are viable, I’m a fan of using transients unless the dataset is exceptionally large or if there is some need to automate the process.

Without seeing much of your current code, it’s difficult to give a working example. Nonetheless, if you end up going the route of transients, I’d recommend something like this:

// Now, check to see if the value is in the cache...
if( !( $our_data = get_transient($key) ) ) {

    // If not, then we'll check the user meta...
    if( !($our_data = get_user_meta($user_id, $key, true)) ) {

        // If not there, we create it and store it.
        $our_data="our data";
        update_user_meta($user_id, $key, $our_data);

    } // end if

    // And we unconditionally update the cache with an expiration of 1 day
    set_transient($key, $our_data, (60 * 60 * 24) );        

} // end if

Generally speaking, the code above will do this:

  • Check the cache to see if the value exists. If the value is found, then nothing else will execute; however, the cache will expire after 24 hours so eventually, it will return null.

  • If the value is not in the cache, then we check the user’s meta data. If it’s there, we use it; otherwise, we’ll manually create it then update the user meta. If the user meta has never been created, WordPress will add it when running the update_user_meta function.

  • Finally, we unconditionally update the cache either with the data in the meta table or with what was manually created.

The only problem with the above code is that if the user meta is never be updated because the above function uses what’s there and only updates it if it’s null. To mitigate this, I’d expect:

  • Either another function elsewhere in your codebase is updating the user value
  • You introduce another conditional to trigger the update function.

For example:

// Contrived. This could be a query, the result of another function, etc.
$user_should_be_updated = true;

if( $user_should_be_updated || !( $our_data = get_user_meta($user_id, $key, true) ) ) {
   /* Create the data, update the user */
} // end if

Manny’s comment also provides some good insight so don’t ignore the answers on that particular question either.