Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm new to using transients. Is this the proper format to create a transient and have it pull from the DB instead of using the http api?

I have standardized my snippet so others can double check their code as well...

function google_transient() {

    $url = 'http://www.google.com';
    $the_whole_body = wp_remote_retrieve_body( wp_remote_get($url) );

    $transient_name = 'google';

    // Get any existing copy of our transient data
    if ( false === ( $transient_name = get_transient( $transient_name ) ) ) {

        // It wasn't there, so regenerate the data and save the transient
         set_transient( $transient_name, $url, 60*24); // 24 hour cache          
    }

    return $the_whole_body;
}
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

No quite: Get the transient’s content first, then do the expensive work to fetch the external resource.

function google_transient() {
    $transient_name = 'google';
    $content        = get_transient( $transient_name );

    // done
    if ( $content )
        return $content;

    $url     = 'http://www.google.com';
    $content = wp_remote_retrieve_body( wp_remote_get($url) );

    set_transient( $transient_name, $content, DAY_IN_SECONDS ); // 24 hour cache          

    return $content;
}
share|improve this answer
    
Thanks! @toscho –  mattrepublic Oct 10 '12 at 18:59
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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