{"id":46608,"date":"2026-10-05T08:01:51","date_gmt":"2026-10-05T08:01:51","guid":{"rendered":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/?p=46608"},"modified":"2026-10-10T20:04:04","modified_gmt":"2026-10-10T20:04:04","slug":"wordpress-set-transient-not-working","status":"publish","type":"post","link":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wordpress-set-transient-not-working\/","title":{"rendered":"WordPress set_transient Not Working? Causes and a Fix"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">You wrapped a slow query in <code>set_transient()<\/code> to speed up a slow WordPress page, yet Query Monitor still shows the query on every load. The usual culprit isn&#8217;t the Transients API. It&#8217;s one of a few edge cases that make <code>get_transient()<\/code> look like a miss even after the value was saved.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The snippet below is a small <code>dpc_remember()<\/code> helper that avoids those edge cases. You give it a key, a lifetime and a callback. The callback runs once and its result is reused until it expires or you clear it. It also caches <code>false<\/code>, <code>0<\/code>, <code>''<\/code> and empty arrays, which a plain transient can&#8217;t do reliably.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why set_transient seems not to work<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>You cached <code>false<\/code>.<\/strong> <code>get_transient()<\/code> returns <code>false<\/code> on a miss, so a stored <code>false<\/code> can&#8217;t be told apart from a miss and your code recomputes every time. An empty <code>get_posts()<\/code> result has a similar problem if you check it with <code>if ( ! $cached )<\/code>.<\/li>\n\n\n<li><strong>The key is too long.<\/strong> Transient names are limited to 172 characters. If you build a key from query args or a URL, it can go over that limit and <code>set_transient()<\/code> returns <code>false<\/code>.<\/li>\n\n\n<li><strong>The expiration is 0.<\/strong> With no expiry, the transient never expires and its option is autoloaded on every request (unless an object cache is active). On a big site that makes <strong>every<\/strong> page slower.<\/li>\n\n\n<li><strong>You cached a <code>WP_Error<\/code>.<\/strong> A failed API call or query gets stored and served for an hour.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">The snippet<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">&lt;?php\n\/**\n * dpc_remember(): a transient helper that also caches false, 0, '' and &#91;&#93;.\n *\/\n\n\/**\n * Return a cached value, or compute it once and cache it for $ttl seconds.\n *\/\nfunction dpc_remember( string $key, int $ttl, callable $callback ): mixed {\n\t$name   = dpc_transient_name( $key );\n\t$cached = get_transient( $name );\n\n\t\/\/ Values are wrapped, so false, 0, '' and &#91;&#93; are real hits.\n\tif ( is_array( $cached ) &amp;&amp; array_key_exists( 'v', $cached ) ) {\n\t\treturn $cached&#91;'v'&#93;;\n\t}\n\n\t$value = $callback();\n\n\t\/\/ Never cache failures.\n\tif ( is_wp_error( $value ) ) {\n\t\treturn $value;\n\t}\n\n\t\/\/ A TTL of 0 means \"never expires\" and autoloads the option: refuse that.\n\tset_transient( $name, array( 'v' =&gt; $value ), max( MINUTE_IN_SECONDS, $ttl ) );\n\n\treturn $value;\n}\n\n\/**\n * Delete a value stored with dpc_remember().\n *\/\nfunction dpc_forget( string $key ): bool {\n\treturn delete_transient( dpc_transient_name( $key ) );\n}\n\n\/**\n * Hash the key so it never exceeds the 172-character transient limit.\n *\/\nfunction dpc_transient_name( string $key ): string {\n\treturn 'dpc_' . md5( $key );\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Add it with Scripts Organizer<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In <a href=\"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/dplugins.com\/downloads\/scripts-organizer\/\">Scripts Organizer<\/a> go to <strong>Code Blocks \u2192 Add New<\/strong> and give the block a name. Set <strong>Trigger location<\/strong> to <strong>Everywhere<\/strong>, tick <strong>PHP<\/strong> under <strong>Script location<\/strong>, paste the code into the PHP editor and publish. Leave <strong>Action\/Hook<\/strong> empty. Everywhere loads the helper on every request, front end, admin, REST and cron, so your theme and other snippets can call it from their hooks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer a file? Put the same code in an mu-plugin (<code>wp-content\/mu-plugins\/dpc-remember.php<\/code>) or in your theme&#8217;s <code>functions.php<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using it<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Here is a real example: the IDs of the five newest posts, cached for an hour and cleared as soon as a post is saved, so visitors never see a stale list. Put it in your theme or in a second code block.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">function dpc_get_recent_post_ids(): array {\n\treturn dpc_remember(\n\t\t'recent_post_ids',\n\t\tHOUR_IN_SECONDS,\n\t\tstatic function (): array {\n\t\t\treturn get_posts(\n\t\t\t\tarray(\n\t\t\t\t\t'post_type'     =&gt; 'post',\n\t\t\t\t\t'post_status'   =&gt; 'publish',\n\t\t\t\t\t'numberposts'   =&gt; 5,\n\t\t\t\t\t'fields'        =&gt; 'ids',\n\t\t\t\t\t'no_found_rows' =&gt; true,\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t);\n}\n\nadd_action( 'save_post_post', 'dpc_flush_recent_post_ids' );\nadd_action( 'deleted_post', 'dpc_flush_recent_post_ids' );\n\nfunction dpc_flush_recent_post_ids(): void {\n\tdpc_forget( 'recent_post_ids' );\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">How it works<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The value is stored as <code>array( 'v' =&gt; $value )<\/code>. A miss is still <code>false<\/code>, but a hit is always an array that has a <code>v<\/code> key. That way a cached <code>false<\/code> or empty array counts as a hit.<\/li>\n\n\n<li><code>dpc_transient_name()<\/code> hashes your key into a fixed 36-character name. You can pass a long key like <code>'report_' . wp_json_encode( $args )<\/code>.<\/li>\n\n\n<li>The lifetime is never less than a minute, so you can&#8217;t accidentally create a never-expiring, autoloaded transient.<\/li>\n\n\n<li><code>WP_Error<\/code> results are returned but not stored, so the next request tries again.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Gotchas<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Call it from a hook.<\/strong> Scripts Organizer loads its code blocks while plugins load, so another plugin&#8217;s file, or an mu-plugin, that calls <code>dpc_remember()<\/code> at the top level runs before the helper exists. Call it on <code>init<\/code> or later, which is where real caching code runs anyway. If an mu-plugin needs it earlier, keep the helper in an mu-plugin file instead.<\/li>\n\n\n<li><strong>With a persistent object cache<\/strong> (Redis, Memcached), transients never reach <code>wp_options<\/code>. They live in the cache and can be evicted early. Treat a transient as &#8220;may disappear any time&#8221;, never as storage.<\/li>\n\n\n<li><strong>Clear on change, don&#8217;t wait for expiry.<\/strong> Hook <code>dpc_forget()<\/code> to the event that makes the data stale (<code>save_post_{type}<\/code>, <code>edited_term<\/code>, <code>updated_option<\/code>), as in the example.<\/li>\n\n\n<li><strong>Cache stampede.<\/strong> When a popular key expires, several requests can run the callback at the same moment. For very expensive callbacks, refresh the value from WP-Cron before it expires so visitors never trigger it.<\/li>\n\n\n<li><strong>Expired transients.<\/strong> Without an object cache, WordPress removes expired transients from the database once a day via cron. If WP-Cron is disabled, set up a real cron job, or <code>wp_options<\/code> keeps growing.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Want to check which queries are still slow after caching? The <code>$wpdb<\/code> helpers in <a href=\"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wpdb-object-good-to-know-methods\/\">WPDB Object good to know methods<\/a> help, and if the admin is slow rather than the front end, look at <a href=\"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/modify-or-disable-heartbeat-api-without-plugin\/\">the Heartbeat API<\/a> first.<\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>Why get_transient() keeps missing in WordPress and your expensive code runs on every load, plus a helper that caches false, empty and long-keyed values.<\/p>\n","protected":false},"author":1,"featured_media":46772,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"WordPress set_transient Not Working? Causes and a Fix","description":"Why get_transient() keeps missing in WordPress and your expensive code runs on every load, plus a helper that caches false, empty and long-keyed values."},"_slim_seo_primary_term_category":0,"_slim_seo_primary_term_post_tag":0,"footnotes":""},"categories":[132,3],"tags":[154,155,153,139,152],"dpc_library":[204],"class_list":["post-46608","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-performance","category-wordpress","tag-caching","tag-database","tag-performance","tag-php","tag-transients"],"_links":{"self":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/46608","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/comments?post=46608"}],"version-history":[{"count":2,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/46608\/revisions"}],"predecessor-version":[{"id":46771,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/posts\/46608\/revisions\/46771"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/media\/46772"}],"wp:attachment":[{"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/media?parent=46608"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/categories?post=46608"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/tags?post=46608"},{"taxonomy":"dpc_library","embeddable":true,"href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/code.dplugins.com\/wp-json\/wp\/v2\/dpc_library?post=46608"}],"curies":[{"name":"wp","href":"https:\/\/summer-heart-0930.chufeiyun1688.workers.dev:443\/https\/api.w.org\/{rel}","templated":true}]}}