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.

Topic transient plugin-development plugins Wordpress

Category Web


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


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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.