1

I am setting up a transient with one hour expiry time. Now i want to know how much time left for the transient to expire.

I am getting the transient timeout value with get_option function.

Can anyone help me out.

Thank You.

2

There is no built-in WordPress function to get the transient timeout. But you can use the following function to get the transient timeout.

function get_transient_timeout( $transient ) {
    global $wpdb;
    $transient_timeout = $wpdb->get_col( "
      SELECT option_value
      FROM $wpdb->options
      WHERE option_name
      LIKE '%_transient_timeout_$transient%'
    " );
    return $transient_timeout[0];
}
  • Just realized that you asked for the time left. This function will return the expiration time. To get the time left, subtract the current time. – Nathan Johnson Dec 4 '16 at 17:53
  • 1
    Hi @Nathan thanks for the reply. We can the same by get_option() function in wordpress. – chaitanya Dec 6 '16 at 5:48
  • I'm not sure I understand your question then. The value of the transient timeout is a UNIX time stamp, so to get the time left, just subtract time(). – Nathan Johnson Dec 7 '16 at 23:50
  • The WordPress set_transient() function does use the PHP time() function for the current time value. If you want to calculate the time remaining for transients using SQL, you can use a query like SELECT o.*, option_value - UNIX_TIMESTAMP() AS seconds_remaining, FROM_UNIXTIME(option_value) as utc_expiration FROM wp_options o WHERE o.option_name LIKE '_transient_timeout_%' ORDER BY o.option_id desc LIMIT 100; – Martin_W Feb 24 '19 at 3:04
  • should return ($transient_timeout) ? $transient_timeout[0] : false; – gordie Mar 21 '19 at 11:07
1

The problem here is that if the site is actually using something like Redis, or any other supported "external cache" then nothing is going to actually be set in the options table (which can be checked with wp_using_ext_object_cache)

Storage in the options table is just how WordPress handles transients outside of any external caching (or local object caching).

With that said, to calculate the time remaining, you would do something like this:

$expires = (int) get_option( '_transient_timeout_MY_TRANSIENT_NAME', 0 );
$time_left = $expires - time();

The value for expiration is calculated by adding time() to the value passed when setting the transient, so to get time left, just subtract time() from the value set for expiration

0

Transients by definition can expire at any moment, no matter what interval you have requested, therefor the "time till expiry" can not be reliably determined. you can hack something by inspecting the "raw" option, but it is a bad idea to relay on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.