Any reason why wp_cache_set not to work?

The wp_cache_*() functions are non-persistent caches which means that they only last during the current page request. This would be beneficial if you’re requesting the same information multiple times during page load. For example, if you’re showing recent posts in the header, content section, and sidebar ( calling the same code 3 times to retrieve recent posts ) then caching the results would be beneficial. Check out The Codex on WP Object Cache for more information.

If you want to save these through multiple page page loads but also expire them eventually, you may want to save them as a transient. They work the same way as the WP Object Cache but they are saved to the database for a set amount of time. If requested and that time has passed, the transient becomes expired and returns false.

$related_post_ids = get_transient( 'theme_related_post_ids' );

if( false === $related_post_ids ) {

    $args = array(
        'fields' => 'ids',  // If we only need IDs, just return IDs
    );
    $the_query = get_posts( $args );

    if( ! empty( $the_query ) ) {
        set_transient( 'theme_related_post_ids', $the_query, 300 );
    }

}

Depending on how many recent posts you’re planning to get, this is probably fruitless. 300 miliseconds is not a very long time and it would probably be faster just calling the query itself during load than attempting to store and retrieve them via cache, but I don’t know your entire use-case.

Leave a Comment