wp cache add
Overview
Write a value to the WordPress object cache only if the key doesn't exist yet. This is the safe non-overwrite version of wp cache set, mirroring the wp_cache_add() function used in plugin code.
What It Does
wp cache add calls wp_cache_add() — which only stores the value if no entry exists for the given key and group. If a value is already cached, the command returns false and does nothing.
Syntax
wp cache add <key> <value> [<group>] [<expiration>]
Arguments
| Argument | Default | Description |
|---|---|---|
KEY | — | Cache key string |
VALUE | — | Value to store |
GROUP | default | Cache group namespace |
EXPIRATION | 0 | TTL in seconds (0 = no expiration) |
Basic Usage
Add a key only if it doesn't exist
wp cache add my_lock "1" locks 60
Add with group and TTL
wp cache add rate_limit_user_42 "1" rate_limits 300
Real-World Scenarios
Scenario 1: Test "first-writer wins" caching pattern
# First write succeeds
wp cache add bootstrap_key "initial_value" default 3600
wp cache get bootstrap_key default # Returns: initial_value
# Second write is a no-op
wp cache add bootstrap_key "other_value" default 3600
wp cache get bootstrap_key default # Still returns: initial_value
Scenario 2: Test cache locking behavior
# Simulate acquiring a cache lock
if wp cache add "cron_lock" "1" locks 60; then
echo "Lock acquired — running cron..."
# ... do work ...
wp cache delete "cron_lock" locks
else
echo "Lock held by another process — skipping."
fi
add vs set
| Command | Behaviour if key exists |
|---|---|
wp cache add | No-op — does not overwrite |
wp cache set | Overwrites existing value |
Best Practices
- Use
addfor test-and-set patterns — simulating cache locks, first-initialization, and idempotent cache warming. - Always check the return in scripts — a failed
addsilently leaves the existing value.
Quick Reference
wp cache add <key> <value> # Default group, no expiry
wp cache add <key> <value> <group> <ttl> # All options
wp cache get <key> <group> # Check what's in cache
Next Steps
wp cache set— force-write, overwriting any existing value.wp cache get— verify cache contents.wp cache delete— remove a cache entry.