Set WordPress Transient Expiration via Variable Value

I want to set WordPress Transient via Variable Value.

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

<?php 
    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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

$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.

Method 2

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 );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x