Skip to main content

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​

ArgumentDefaultDescription
KEY—Cache key string
VALUE—Value to store
GROUPdefaultCache group namespace
EXPIRATION0TTL 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​

CommandBehaviour if key exists
wp cache addNo-op — does not overwrite
wp cache setOverwrites existing value

Best Practices​

  1. Use add for test-and-set patterns — simulating cache locks, first-initialization, and idempotent cache warming.
  2. Always check the return in scripts — a failed add silently 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​