WordPress.org

Make WordPress Core

Ticket #15447: 15447.diff

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

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

  • wp-includes/post-thumbnail-template.php

    diff --git wp-includes/post-thumbnail-template.php wp-includes/post-thumbnail-template.php
    index 3758d1d..3ad64cf 100644
    function the_post_thumbnail( $size = 'post-thumbnail', $attr = '' ) { 
    4848}
    4949
    5050/**
     51 * Update cache for thumbnails in current loop
     52 *
     53 * @since 3.2
     54 */
     55function update_thumbnail_cache() {
     56        global $wp_query;
     57
     58        $cache_key = 'thumb_cache:' . md5( implode( ',', wp_list_pluck( $wp_query->posts, 'ID' ) ) );
     59       
     60        // return if this loop is already cached
     61        if ( wp_cache_get( $cache_key, 'thumbnails' ) )
     62                return;
     63
     64        $thumb_ids = array();
     65        foreach ( $wp_query->posts as $post ) {
     66                if ( $id  = get_post_thumbnail_id( $post->ID ) )
     67                        $thumb_ids[] = $id;
     68        }
     69
     70        if ( ! empty( $thumb_ids ) ) {
     71                $thumb_ids = array_filter( array_unique( $thumb_ids ) );
     72
     73                get_posts( array(
     74                        'update_post_term_cache' => false,
     75                        'include'                => $thumb_ids,
     76                        'post_type'              => 'attachment',
     77                        'post_status'            => 'inherit',
     78                        'nopaging'               => true,
     79                ) );
     80        }
     81       
     82        wp_cache_add( $cache_key, 1, 'thumbnails', 86400 ); // 1 day
     83}
     84
     85/**
    5186 * Retrieve Post Thumbnail.
    5287 *
    5388 * @since 2.9.0
    function get_the_post_thumbnail( $post_id = null, $size = 'post-thumbnail', $att 
    6297        $size = apply_filters( 'post_thumbnail_size', $size );
    6398        if ( $post_thumbnail_id ) {
    6499                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
     100
     101                if ( in_the_loop() )
     102                        update_thumbnail_cache();
     103
    65104                $html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr );
    66105                do_action( 'end_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size );
    67106        } else {