Skip to main content

wp cache set

Overview

Write an arbitrary value to the WordPress object cache under a specific key and group. Use this for testing plugin caching logic, warming specific cache keys, or debugging cache behavior from the CLI.

What It Does

wp cache set calls wp_cache_set() to store a value. Unlike wp cache add, it overwrites any existing value for the given key and group. The value expires after EXPIRATION seconds, or never if 0.

Syntax

wp cache set <key> <value> [<group>] [<expiration>]

Arguments

ArgumentDefaultDescription
KEYCache key string
VALUEValue to store
GROUPdefaultCache group namespace
EXPIRATION0TTL in seconds (0 = no expiration)

Basic Usage

Set a simple key-value pair

wp cache set my_feature_flag "enabled" default 3600

Set in a specific group with no expiration

wp cache set product_count "1247" counts 0

Overwrite an existing value

wp cache set my_key "new_value" default

Real-World Scenarios

Scenario 1: Test cache warm-up for a plugin

# Simulate a plugin warming its cache
wp cache set "wc_product_loop_1" '{"ids":[12,15,18]}' "wc_loop" 3600

# Verify
wp cache get "wc_product_loop_1" "wc_loop"

Scenario 2: Test cache expiration behavior

# Set a 5-second cache entry
wp cache set test_expiry "value123" default 5

# Immediately get it
wp cache get test_expiry default # Returns: value123

# Wait 6 seconds then check
sleep 6
wp cache get test_expiry default # Cache miss

Scenario 3: Warm site-wide counters

wp cache set total_published_posts "$(wp post list --post_status=publish --format=count)" counts 86400

set vs add

CommandBehaviour if key exists
wp cache setOverwrites the existing value
wp cache addSkips — does NOT overwrite

Best Practices

  1. Use set for intentional overwrites — use add when you only want to write if nothing is cached yet.
  2. Always specify a TTL for non-permanent cache entries to prevent stale data.
  3. Use this primarily for testing — production cache writes should happen through WordPress APIs.

Quick Reference

wp cache set <key> <value>                   # Default group, no expiry
wp cache set <key> <value> <group> <ttl> # All options
wp cache get <key> <group> # Verify the value

Next Steps