最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

WordPress transient doesn't use the transient

programmeradmin3浏览0评论

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( ';_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?

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/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?

Share Improve this question edited Aug 27, 2020 at 7:27 bueltge 17.1k7 gold badges62 silver badges97 bronze badges asked Aug 26, 2020 at 20:21 lolikiloliki 1851 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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
}
发布评论

评论列表(0)

  1. 暂无评论