WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a results set being returned from the database. How can I use wp_cache to speed this up?

function bb_attachments_cache() {
    global $wp, $bp, $wpdb, $posts, $bb_attachments, $bb_attachments_cache, $bbdb;

    $all_posts_query = "SELECT `post_id` FROM $bbdb->posts";
    $posts = $bbdb->get_results( $all_posts_query );
    foreach ($posts as $post)  {
        $bb_attachments_cache[$post->post_id] = array();

    $sql = "SELECT 
    FROM bb_posts bbp
    JOIN bb_attachments bba
    ON bba.post_id = bbp.post_id
    ORDER BY id DESC";

    $attachments = $wpdb->get_results($sql);

    if ($attachments){

        foreach ($results as $result){
            $bb_attachments_cache[$result->post_id][$result->id] = $result;



I want to set the cache object if there has been any updates to the attachments table. Im using wordpress 3.1 and have a caching plugin installed and working.

share|improve this question

If you move to using BBpress 2, BBpress 2 uses custom post types and is a plugin of WordPress. This would let you do the above query using standard WordPress calls, and WP_Query. You would then automatically inherit all of the caching systems WordPress uses, and support for things like W3 Total Cache DB caching etc

Else, you could use the Wordpress Transients API to cache the results:


share|improve this answer
Thanks Tom. However, im using bbpress for wordpress-buddypress, and this plugin is an forum-attachments for buddypress bb-press. :-} Im thinking i can use the wp_cache_set now i have the cache plugin installed. But dont have much experience with caching. Is it easy to check if query results have changed and use caching. Im think the caching it uses right now isnt persistent, cause this $bb_attachments_cache array build is slowing everything down. – madphp Nov 18 '11 at 14:02
you'd need a hook in bbpress that clears and resets the cache in wordpress – Tom J Nowell Nov 18 '11 at 15:18

Your Answer


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.