Ticket #15447: 15447.diff

File 15447.diff, 1.8 KB (added by garyc40, 2 years ago)

cache post thumbnails on first call of get_the_post_thumbnail() in a loop

Line 
1diff --git wp-includes/post-thumbnail-template.php wp-includes/post-thumbnail-template.php
2index 3758d1d..3ad64cf 100644
3--- wp-includes/post-thumbnail-template.php
4+++ wp-includes/post-thumbnail-template.php
5@@ -48,6 +48,41 @@ function the_post_thumbnail( $size = 'post-thumbnail', $attr = '' ) {
6 }
7 
8 /**
9+ * Update cache for thumbnails in current loop
10+ *
11+ * @since 3.2
12+ */
13+function update_thumbnail_cache() {
14+       global $wp_query;
15+
16+       $cache_key = 'thumb_cache:' . md5( implode( ',', wp_list_pluck( $wp_query->posts, 'ID' ) ) );
17+       
18+       // return if this loop is already cached
19+       if ( wp_cache_get( $cache_key, 'thumbnails' ) )
20+               return;
21+
22+       $thumb_ids = array();
23+       foreach ( $wp_query->posts as $post ) {
24+               if ( $id  = get_post_thumbnail_id( $post->ID ) )
25+                       $thumb_ids[] = $id;
26+       }
27+
28+       if ( ! empty( $thumb_ids ) ) {
29+               $thumb_ids = array_filter( array_unique( $thumb_ids ) );
30+
31+               get_posts( array(
32+                       'update_post_term_cache' => false,
33+                       'include'                => $thumb_ids,
34+                       'post_type'              => 'attachment',
35+                       'post_status'            => 'inherit',
36+                       'nopaging'               => true,
37+               ) );
38+       }
39+       
40+       wp_cache_add( $cache_key, 1, 'thumbnails', 86400 ); // 1 day
41+}
42+
43+/**
44  * Retrieve Post Thumbnail.
45  *
46  * @since 2.9.0
47@@ -62,6 +97,10 @@ function get_the_post_thumbnail( $post_id = null, $size = 'post-thumbnail', $att
48        $size = apply_filters( 'post_thumbnail_size', $size );
49        if ( $post_thumbnail_id ) {
50                do_action( 'begin_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size ); // for "Just In Time" filtering of all of wp_get_attachment_image()'s filters
51+
52+               if ( in_the_loop() )
53+                       update_thumbnail_cache();
54+
55                $html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr );
56                do_action( 'end_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size );
57        } else {