How wp_cache is supposed to work, and does it help with performance?

I was coding my recent comments widget, and using $wpdb->get_results and I wanted t use cache so it doesn’t perform the query every time the page loads, so I used:

$comments = wp_cache_get('mycomments');
if ($comments == false) {
    $query = //some sql stuff
    $comments = $wpdb->get_results($query);
    wp_cache_set('mycomments', $comments);
}
//then use $comments

and I used WP Cache Inspect plugin to check if it’s working, I tried setting the $expire value in wp_cache_set in 2 ways ‘9999’ and 9999 and deleted the cache between the 2 test but it doesn’t seem to work for me, I commented on an article and it showed immediately in the recent comments so it seems that it’s not caching the query for 9999 seconds, so is this how it’s supposed to work or am I doing something wrong ?

and thanks in advance.

EDIT: I was checking the codex there’s also Transients API but limited to 45 characters, so what’s the difference between this and wp_cache ? this one seemd to store data in the database.

2 Answers
2

In WordPress v2.5+ the object cache is not persistent. It will save things in memory, but for persistent caching across page loads you will need a plugin see here:

http://codex.wordpress.org/Class_Reference/WP_Object_Cache#Persistent_Caching

Alternatively, use transients, which are persistent. The identifier must be 45 or less characters long, but the data attached to that identifier can be longer. Keep in mind that storing very large amounts of data this way is not recommended.

Leave a Comment