1

I'm new to the transients but I think I get the logic behind it.

So I have a blog and I grab the posts via the API from another blog of mine.

Now I would like to save the data in a transient so I don't make a request every time I visit the page.

Here is my code:

if (false === ($posts === get_transient('posts_array'))) {

    $response = wp_remote_get( 'https://website.com/blog/wp-json/wp/v2/posts?per_page=5&_embed' );
    // Exit if error.
    if ( is_wp_error( $response ) ) {
        return;
    }
        
    $posts[] = json_decode( wp_remote_retrieve_body( $response ) );

    set_transient('posts_array', $posts, DAY_IN_SECONDS);
}

Now for some reason my WordPress doesn't get the transients it seems that it always makes the request to the API to get the $posts should I somewhere assign $posts with get_transient if it exists?

2

I mean in shortly your code is wrong in the first line, the comparing is wrong. The variable $post should store = the data of the request via get_transient() and not compare ===.

So you should switch to:

if ( false === ( $posts = get_transient('posts_array') ) ) {
    // this code runs when there is no valid transient set
}
| improve this answer | |

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.