WordPress Transients: How to Name Transient Keys

WordPress Transients: How to Name Transient Keys

A WordPress transient is cached data with an expiration. When you store an API response or an expensive query result, you give it a transient key, a value, and a lifetime. The one rule people get wrong is the key, so here is how to name a transient key that will not silently break.

What transients are

The Transients API is three functions:

  • set_transient( $key, $value, $expiration ) stores the value for $expiration seconds.
  • get_transient( $key ) returns the value, or false once it has expired.
  • delete_transient( $key ) removes it early.

By default transients live in the wp_options table. If a persistent object cache (Redis or Memcached) is active, they live there instead and the database is skipped. Either way, your code does not change. You always read and write through the same key.

The 172-character key limit

This is the part that bites people. Transient names should be 172 characters or fewer.

The reason is how WordPress stores them. When a transient lands in wp_options, WordPress creates two rows: one named _transient_yourkey for the value, and one named _transient_timeout_yourkey for the expiry timestamp. The longer prefix, _transient_timeout_, is 19 characters. The option_name column is capped at 191 characters. That leaves 191 minus 19, which is 172 characters for your actual key.

Go over 172 and the timeout row gets truncated. The value row and the timeout row no longer match, so the transient never expires correctly or never reads back. The failure is quiet, which is the worst kind. Keep keys at 172 characters or fewer and you stay safe whether or not an object cache is in play.

Name keys with a prefix and a hash

Two conventions keep keys short, unique, and collision-free:

  1. Prefix every key with your plugin or theme slug, like myplugin_ or acme_blog_. This namespaces your transients so they never clash with core or another plugin.
  2. Hash the variable part. When the cached data depends on inputs (a user ID, query args, a URL), do not paste those raw values into the key. Run them through md5() and append the result. An MD5 is always 32 characters, so your key stays short and predictable no matter how large the input.

A typical key looks like myplugin_posts_ followed by md5( serialize( $query_args ) ). Stable, unique, and well under 172 characters.

The WordPress Transient Key Generator builds these for you and flags anything too long before it reaches your database.

Generate a safe key

  1. Open the WordPress Transient Key Generator.
  2. Enter your prefix and the variable parts you want hashed.
  3. Copy the generated key, which is already validated against the 172-character limit, straight into set_transient().

It runs entirely in your browser, so nothing you type is sent anywhere.

Prefix it, hash the variable part, keep it under 172 characters, and your transients will just work.

← All posts