As we have seen previously seen what the Transient API is in WordPress, this blog explores the best practices and other things to keep in mind when using the Transient API to ensure efficiency, integrity and speed of our website.

Best Practices for Using Transient API

Appropriate Expiration Time

Transients are intended for temporary storage so its important to set correct expiration time based on how often the data changes. For example some event data might only change a few times a day so setting the transient to expire in an hour will be optimal. However if the expiration is too big the cached data may become stale.

Delete Transients When Appropriate

Itโ€™s important to clear transients when data changes. We can use hooks to delete a transient when a new post/data modified. This ensures that the cache reflects the most current data.

Store Only the Necessary Data

Transients should store only the data that is necessary for quick access. We usually store the post IDs, but if we needed additional data like custom fields, we could retrieve that data only when necessary, ensuring we don’t store excessive information in the cache.

Using Transients for Expensive Operations

Use transients to cache results of expensive operations such as API calls, database queries, or other heavy computations. This reduces the need to repeat these operations on every page load and can significantly speed up our site.

Example: Using Transient API for Displaying Latest Events

function latest_events_shortcode() {
    $args = array(
        'post_type' => 'my_event',
        'posts_per_page' => 5,
        'orderby' => 'DESC'
    );

    // Check if the transient already exists
    $latest = get_transient('latest_events');

    // If the transient doesnt exist query the database and set a new transient
    if ( ! $latest ) {
        // Query the posts
        $query = new WP_Query($args);

        $events = array();

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $events[] = get_the_ID();
            }
            wp_reset_postdata();
        }

        set_transient('latest_events', $events, 1 * HOUR_IN_SECONDS);
        $latest = get_transient('latest_events');
    }
    ob_start();
    if ($latest) {
        foreach ($latest as $event) {
            echo '<h2>' . get_the_title($event) . '</h2>';
        } 
    } else {
        echo 'No Events Found';
    }
    return ob_get_clean();
}
add_shortcode('latest', 'latest_events_shortcode');

// Clear the transient when new event is saved or updated
add_action('save_post_my_event', function () {
    delete_transient('latest_events');
});
  1. Checking the Transient: The function get_transient('latest_events') attempts to fetch the latest events from the cache.
  2. Querying the Database: If the transient doesn’t exist we run a query to fetch the latest events and store the results in a transient.
  3. Setting the Transient: We store the event IDs in the transient.
  4. Displaying the Events: If the transient exists, we loop through the event IDs and display the titles of the events.
  5. Cache Invalidation: The delete_transient('latest_events') action ensures that the cache is cleared when a new event is saved or an existing event is updated, so that the cache stays up to date.

Conclusion

The WordPress Transient API is a simple yet powerful tool that can help us optimize the performance of our websites by caching expensive queries or external API calls.

By following best practices such asโ€” setting appropriate expiration times, deleting expired transients and storing only important information we can improve the user experience by delivering content faster while reducing the load on our servers.

Leave a Reply

Your email address will not be published. Required fields are marked *