Filtering transient expiration time in WordPress

As of now WordPress, doesn't offer a filter to control the expiration of the transient while its being set, so I quickly wanted to share a quick snippet I found on Trac, written by Andrew Nacin.

Here is the snippet:

<?php
add_action( 'set_transient_my_transient', function( $value, $expiration ) {
$desired_expiration = 600;
if ( $expiration != $desired_expiration ) {
set_transient( 'my_transient', $value, $desired_expiration );
}
});

Basically, 'set_transient_' . $transient hook is fired once the transient gets saved, so it saves itself again resulting in recursion as the same hook will be fired again, but before it saves itself again, it checks whether the $desired_expiration is different from the $expiration with which it's being saved. Smart!

On a side note, if you ever need to do this, don't use anonymous functions because that takes away the ability to unhook your function by someone else. Its just a quick way to demonstrate the idea.

Concerned Trac Ticket - https://core.trac.wordpress.org/ticket/21330

Published by

Ashfame

Developer + Entrepreneur + Open Source fanatic.

Love WordPress + Startups + Adventure + Music.

  • Shivansh Katoch

    Quite helpful post. Thanks for sharing.