I want to set WordPress Transient via Variable Value.

This is an example code with what I'm trying to achieve.

    if ( false === get_transient( 'special_query_results' ) ) {
        $ExpiryInterval = "24 * HOUR_IN_SECONDS"; // <--- Storing in Variable

        $RandPostQuery = new WP_Query(array('post_type'=>array('tip'),'posts_per_page' => 1,'orderby'=>'rand'));

        set_transient( 'special_query_results', $RandPostQuery , $ExpiryInterval ); // <-- Retriving from Variable

I don't know why it's not working. If I try setting directly without variable it's working perfectly. Not sure why it's not working this way.

$ExpiryInterval = "24 * HOUR_IN_SECONDS";

$ExpiryInterval is being assigned a string, but you need a number.

Consider this example:

$foo = 5 * 10;
$bar = "5 * 10";

The value of $foo is 50. The value of $bar is "5 * 10". set_transient expects a number, not a string, "24 * HOUR_IN_SECONDS" is text/string, 24 * HOUR_IN_SECONDS is a number. HOUR_IN_SECONDS is a constant equal to the number of seconds in an hour.

  • 1
    Hey Tom, Thanks for making it clear to understand. I got it working. Thanks a lot. – Ava Juan Mar 5 at 19:37

HOUR_IN_SECONDS is a WordPress constant - you cannot put a constant inside a variable and expect PHP to know it's a constant and not a string when it is parsed. In your example code, I'd just simplify it:

set_transient( 'special_query_results', $RandPostQuery , 24 * HOUR_IN_SECONDS ); 

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.