WordPress transient doesn't use the transient

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?

Topic transient Wordpress

Category Web


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
}

About

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