1

What is the best way to store data? Database, cache, etc?

I want to build a widget, which will show some data from API, but I don't want to call API every time, because of limits. I'd like to call API every 3 hours or once a day and store data from API and timestamp when API was called.

How to do it?

Sorry, don't have a code to show. It's more theoretical question

1

2 Answers 2

2

You probably want to look at using WordPress Transients as they can handle both the data and the timestamp/expiration.

You can also check out The Deal with WordPress Transients by CSS Tricks which has some good info as well.

0
1

For such purposesTransient API is the right choice to use.

From Codex page:

Transient API offers a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted.

...

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. Transients should also never be assumed to be in the database, since they may not be stored there at all.

Example code

How to SET Transients

set_transient( $transient, $value, $expiration );

$transient

(string) Transient name. Expected to not be SQL-escaped. Must be 172 characters or fewer in length.

$value

(array|object) Data to save, either a regular variable or an array/object. The API will handle serialization of complex data for you.

$expiration

(integer) The maximum of seconds to keep the data before refreshing. Transients may expire before the $expiration (Due to External Object Caches, or database upgrades) but will never return their value past $expiration.

So for example to save the $special_query_results object for 12 hours you would do:

set_transient( 'special_query_results', $special_query_results, 60*60*12 );

How to GET transient

get_transient( $transient );

$transient the unique slug used while saving the transient with set_transient().

In our case we could fetch our special query results with:

get_transient( 'special_query_results' );

If the transient does not exist, or has expired, then get_transient() will return false. This should be checked using the identity operator (===) instead of the normal equality operator (==), because an integer value of zero (or other "empty"/"falsey" 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 (true/false). Put them into an array or convert them to integers instead.

Example usage:

if ( false === ( $value = get_transient( 'value' ) ) ) {
     // this code runs when there is no valid transient set
}

The above code will get the transient and put it into $value. The code inside the if block only runs when there's not a valid transient for it to get. This is typically a method to re-generate the transient value through other means. Keep in mind that it's possible for a transient to not be available before it's normal expiration time.

Complete Example

function wp1707_get_my_api_data ( $update = false ){
    // Checking if our transient is available.
    $my_api_data = get_transient( 'wp1707_my_api_data' );

    // Is transient data not available or do we want to force the update?
    if ( empty( $my_api_data ) || !$update) {

        // Get the data from API
        $my_api_data = call_to_my_api();
        // Now let's set that data as transient and store it for 3hours
        set_transient( 'wp1707_my_api_data', $my_api_data, 3 * HOUR_IN_SECONDS );
    }

    // 
    return $my_api_data;
}

Caveats when using Transients API

  1. Transients are time bound but they may expire before the expiration time you set. Always make sure to have fallback in your code.
  2. When caching plugins/mechanisms are used, transients are stored outside of database all together. Never assume or expect transients to be stored inside database.
  3. Make sure that the slug that you use is unique. Generalized slugs such as my_api_data are poor design decision. It's best to pad the slugs with unique prefix/suffix such as wp1707_wcf_my_api_data. This is to ensure that any other poorly designed plugin/theme don't overwrite your transient data.
  4. Transients API is not suitable for every scenario. Read this great post by Pressjitsu - Don't Cache Everything with Transients
  5. This article by CSS-Tricks has some great pointers on pros and cons with example code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.