Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer

wp_cache_set/add functions will store data for you until you manually remove the data from the cache, or the cache collector gets destroyed, whichever happens first.

By default WP stores this data inside an array variable, so the collector would get destroyed on each page load.

Remember to flush cache after operations that modify the data you retrieved. In your case, for comments you might want to clear your cache when a new comment is added:

add_action('comment_post', function(){
  wp_cache_delete('mycomments');
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.