Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 68 ยท Performance, Tools and Scaling

Caching and WP-Cron

Understand page, object and transient caching in WordPress, how to build safe cache keys and invalidate them, and how WP-Cron schedules work with a real system cron.

A WordPress page can trigger dozens of database queries and a lot of PHP work. Doing that again for every visitor is wasteful, because most pages look the same for everyone. Caching means remembering the result of expensive work and reusing it. It is the biggest single speed-up available to most sites, but it also brings the classic problem: stale data. A good cache is fast and knows when to forget.

The second half of this lesson covers WP-Cron, WordPress's scheduler for background jobs such as publishing scheduled posts, checking for updates or sending a daily digest. It is closely related to caching because the two are often combined: a scheduled job warms or refreshes a cache.

Real WordPress code is read-only on this site. The runnable examples are plain-PHP stand-ins with a fake clock, so their output is the same every time you run them.

Three layers of caching

flowchart LR
    V["Visitor"] --> P["Page cache<br/>(whole HTML)"]
    P -->|miss| W["WordPress + PHP"]
    W --> O["Object cache<br/>(query results, objects)"]
    O -->|miss| D[("Database")]
    W --> T["Transients<br/>(remote API data)"]

A request tries the cheapest layer first and falls through to the next one only on a miss.

  1. Page cache stores the finished HTML for a URL. A hit skips PHP and the database completely. It is implemented by a caching plugin (through the advanced-cache.php drop-in and the WP_CACHE constant), by the web server, or by a CDN. It works best for logged-out visitors, because logged-in pages are personal.
  2. Object cache stores PHP values (query results, option values, computed arrays) behind wp_cache_get() and wp_cache_set().
  3. Transients store values with an expiry time, typically the results of slow remote API calls or heavy calculations.

Core uses the object cache constantly: posts, terms, users and options are cached after the first read, so asking for the same post twice in a request runs one query.

The object cache API

PHP
$key   = 'popular_posts_v1';
$group = 'myplugin';

$posts = wp_cache_get( $key, $group, false, $found );

if ( ! $found ) {
    $posts = myplugin_query_popular_posts(); // the slow part
    wp_cache_set( $key, $posts, $group, 5 * MINUTE_IN_SECONDS );
}

The functions you will use: wp_cache_get(), wp_cache_set(), wp_cache_add() (only sets if the key is free), wp_cache_delete(), wp_cache_incr() and wp_cache_decr(), wp_cache_get_multiple() and wp_cache_flush_group() (the last one only works if the cache backend supports it). Always pass the $found argument when the cached value could legitimately be false, 0 or an empty array, so you can tell "cached falsy value" from "not cached".

By default the object cache is non-persistent: it lives for one PHP request and disappears. That still avoids repeated queries inside a single page build, but nothing survives to the next visitor. To keep it between requests, install a persistent object cache: a drop-in file wp-content/object-cache.php, usually provided by a plugin that talks to Redis or Memcached. Your code does not change: the same wp_cache_* calls now read and write the shared in-memory store.

The next stand-in simulates a cache with groups, expiry (using a fake clock), a $found flag and hit/miss counters. Real backends such as Redis or Memcached do the expiry for you, but the logic you write in plugins looks like this.

PHP An object cache with expiry and a found flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Transients

Transients are the object cache with an expiry that survives requests whatever your setup. set_transient( $key, $value, $expiration ), get_transient( $key ) and delete_transient( $key ) store a value for a number of seconds. Without a persistent object cache, transients are saved in the wp_options table (as two rows: the value and its timeout). With a persistent object cache, WordPress stores them in the cache instead and skips the database. The Options API lesson covers their storage in more detail.

PHP
function myplugin_get_exchange_rates(): array {
    $rates = get_transient( 'myplugin_rates' );

    if ( false === $rates ) {
        $response = wp_remote_get( 'https://api.example.com/rates' );

        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
            return array(); // do not cache failures for long
        }

        $rates = json_decode( wp_remote_retrieve_body( $response ), true );
        set_transient( 'myplugin_rates', $rates, HOUR_IN_SECONDS );
    }

    return is_array( $rates ) ? $rates : array();
}

Two cautions. A transient can disappear at any moment (a cache flush, memory pressure, or an expiry), so your code must always cope with a miss. And an expired transient is not guaranteed to be deleted right away, so never use a transient to store data you cannot rebuild.

Cache keys and invalidation

"There are only two hard things in computer science: cache invalidation and naming things." Both show up here. Two habits keep a cache correct:

  • Build keys from everything that changes the result. A cached list for posts_per_page = 5 is not the list for 10. Include the arguments, language or user role if they matter, for example md5( wp_json_encode( $args ) ). Prefix keys with your plugin name and use a group.
  • Invalidate on the events that change the data. Delete or refresh the entry when the underlying data is saved:
PHP
add_action( 'save_post_event', 'myplugin_clear_event_cache' );
add_action( 'deleted_post', 'myplugin_clear_event_cache' );

function myplugin_clear_event_cache(): void {
    wp_cache_delete( 'upcoming_events', 'myplugin' );
    delete_transient( 'myplugin_rates_summary' );
}

For many related keys, a cheap trick is a version key: store a number such as last_changed, include it in every key, and bump it to invalidate them all at once. Core uses this pattern for query caches. Old entries simply stop being read and expire on their own.

Page caches also need purging. When a post changes, the page cache must clear that URL, the home page, and its archives. Most caching plugins listen to save_post and do this for you. If you add custom data that appears on pages (for example, a "stock left" count), either exclude it from the page cache or load it with JavaScript after the page loads.

WP-Cron: scheduled tasks

WordPress needs to run jobs on a schedule, such as publishing a post at a set time (publish_future_post), checking for updates, or cleaning expired data. Unlike a Unix cron daemon, WP-Cron is not a clock. It is a list of due times stored in the cron option, checked when someone visits the site. On each request WordPress sees whether any event is due and, if so, triggers a non-blocking request to wp-cron.php, which runs the due events.

sequenceDiagram
    participant V as Visitor
    participant W as WordPress
    participant C as wp-cron.php
    V->>W: Page request
    W->>W: Is any event due?
    W-)C: Spawn request (non-blocking)
    W-->>V: Page response
    C->>C: Run due hooks
    C->>C: Reschedule recurring events

Cron runs as a side effect of normal traffic, so a quiet site runs jobs late and a busy site checks constantly.

Use it with these functions:

PHP
// A custom interval, if hourly/twicedaily/daily/weekly are not enough.
add_filter( 'cron_schedules', function ( array $schedules ): array {
    $schedules['every_fifteen_minutes'] = array(
        'interval' => 15 * MINUTE_IN_SECONDS,
        'display'  => __( 'Every 15 minutes', 'myplugin' ),
    );
    return $schedules;
} );

// Schedule once, on activation: not on every request.
register_activation_hook( __FILE__, function (): void {
    if ( ! wp_next_scheduled( 'myplugin_refresh_cache' ) ) {
        wp_schedule_event( time(), 'every_fifteen_minutes', 'myplugin_refresh_cache' );
    }
} );

// The hook that does the work.
add_action( 'myplugin_refresh_cache', 'myplugin_refresh_cache_callback' );

// Clean up on deactivation.
register_deactivation_hook( __FILE__, function (): void {
    wp_clear_scheduled_hook( 'myplugin_refresh_cache' );
} );

wp_schedule_event() repeats an event; wp_schedule_single_event() runs it once. wp_next_scheduled() checks whether it is already scheduled, which prevents duplicates when you schedule from code that runs often. wp_unschedule_event() and wp_clear_scheduled_hook() remove events. The event's hook is an ordinary action, so priorities and hooks work as usual. Pass any arguments as an array after the hook name.

Limits and a real cron

WP-Cron has two weaknesses that matter at scale:

  • Late jobs on low-traffic sites, because nothing triggers it without a visit.
  • Overhead on high-traffic sites: every request checks the schedule, and a slow job can overlap with the next one.

The usual fix is to turn off the visit-triggered check and call WordPress from the system's real scheduler:

PHP
// wp-config.php
define( 'DISABLE_WP_CRON', true );
Terminal
# crontab -e   (run every five minutes)
*/5 * * * * cd /var/www/html && wp cron event run --due-now > /dev/null 2>&1

# or, without WP-CLI:
*/5 * * * * curl -s https://example.com/wp-cron.php?doing_wp_cron > /dev/null

Jobs should be idempotent: running one twice must not do harm, because overlaps and retries happen. Keep each job short, and have it process a limited batch and reschedule itself for more if there is more work. Inspect the queue with wp cron event list (see WP-CLI).

The scheduler below simulates the behavior with a fake clock: events have a due time, recurring ones are rescheduled after they run, and nothing happens until a "visit" checks the queue.

PHP A WP-Cron scheduler simulation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that send_digest was due at 5000 but only ran at the visit at 9000, and that each recurring event is rescheduled from the time it ran, not from its original due time. That is how a quiet site drifts, and why a real system cron is the better choice for jobs that need to be punctual.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the default lifetime of the WordPress object cache without a persistent backend?

    By default the object cache lives in PHP memory for a single request. A persistent object-cache drop-in (Redis or Memcached) is needed to keep values between requests.
  2. 2. Why pass the $found argument to wp_cache_get()?

    A miss returns false, which is also a valid cached value. The found flag removes the ambiguity.
  3. 3. When does WP-Cron check for due events by default?

    WP-Cron is triggered by traffic. A site with no visits does not run its scheduled jobs on time, which is why a real system cron is recommended for important jobs.
  4. 4. You set DISABLE_WP_CRON to true. What must you also do?

    That constant only stops the visit-triggered check. Without a real scheduler calling WordPress, no scheduled jobs run at all.
  5. 5. What is the safest way to schedule a recurring event in a plugin?

    Checking wp_next_scheduled() avoids duplicate events, and activation and deactivation hooks keep the schedule tidy.

Summary

  • Caching works in layers: page cache, object cache and transients. A request tries the cheapest layer first.
  • The object cache is per-request until a persistent drop-in (Redis, Memcached) is installed; the code stays the same.
  • Build keys from everything that changes the result, invalidate on the events that change the data, and use $found to detect misses.
  • Transients are cache entries with an expiry; always be ready for them to be missing.
  • WP-Cron runs when visitors arrive, so it is approximate; use DISABLE_WP_CRON plus a system cron for punctual jobs, and make jobs idempotent.

Next, find out where your site actually spends its time: Performance Optimization.