[wp-trac] [WordPress Trac] #15447: Cache Post Thumbnails

WordPress Trac wp-trac at lists.automattic.com
Thu Nov 18 04:42:29 UTC 2010


#15447: Cache Post Thumbnails
-----------------------------+----------------------------------------------
 Reporter:  TheDeadMedic     |       Owner:                               
     Type:  enhancement      |      Status:  new                          
 Priority:  normal           |   Milestone:  Future Release               
Component:  Post Thumbnails  |     Version:                               
 Severity:  normal           |    Keywords:  needs-patch reporter-feedback
-----------------------------+----------------------------------------------

Comment(by johnbillion):

 I've written a plugin which does exactly this. On a large site I'm working
 on with 14 (yeah, fourteen) loops on the home page and thumbnails
 *everywhere* the number of queries was through the roof.

 Here's the relevant code which preloads attachments for all posts in the
 main loop (my custom loops also call the 'loop_start' action - usually
 this is not the case).

 {{{
 function cache_thumbnail_posts( $q ) {
         $types = $thumb_ids = array();
         foreach ( $q->posts as $p )
                 $types[$p->post_type] = $p->post_type;
         unset( $types['attachment'] );
         if ( empty( $types ) )
                 return $q;
         foreach ( $q->posts as $p )
                 $thumb_ids[] = get_post_thumbnail_id( $p->ID );
         $thumb_ids = array_filter( $thumb_ids );
         if ( empty( $thumb_ids ) )
                 return $q;
         $thumb_ids = implode( ',', $thumb_ids );
         $preload = get_posts( 'post_type=attachment&include=' . $thumb_ids
 );
         return $q;
 }
 add_filter( 'loop_start', array( $this, 'cache_thumbnail_posts' ) );
 }}}

 Looks a bit complex but it means it only preloads the attachments when it
 needs to.

 One thing to consider is that this will add unnecessary queries if the
 current theme isn't displaying the post thumbnails in the loop.

 Thoughts?

-- 
Ticket URL: <http://core.trac.wordpress.org/ticket/15447#comment:4>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software


More information about the wp-trac mailing list