WordPress.org

Make WordPress Core

Ticket #15447: 15447.2.diff

File 15447.2.diff, 2.0 KB (added by scribu, 7 years ago)

Check $wp_query->current_post before attempting to cache

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

     
    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        // return if not at loop start
     59        if ( 0 != $wp_query->current_post )
     60                return;
     61
     62        $cache_key = 'thumb_cache:' . md5( implode( ',', wp_list_pluck( $wp_query->posts, 'ID' ) ) );
     63       
     64        // return if this loop is already cached
     65        if ( wp_cache_get( $cache_key, 'thumbnails' ) )
     66                return;
     67
     68        $thumb_ids = array();
     69        foreach ( $wp_query->posts as $post ) {
     70                if ( $id  = get_post_thumbnail_id( $post->ID ) )
     71                        $thumb_ids[] = $id;
     72        }
     73
     74        if ( ! empty( $thumb_ids ) ) {
     75                $thumb_ids = array_filter( array_unique( $thumb_ids ) );
     76
     77                get_posts( array(
     78                        'update_post_term_cache' => false,
     79                        'include'                => $thumb_ids,
     80                        'post_type'              => 'attachment',
     81                        'post_status'            => 'inherit',
     82                        'nopaging'               => true,
     83                ) );
     84        }
     85       
     86        wp_cache_add( $cache_key, 1, 'thumbnails', 86400 ); // 1 day
     87}
     88
     89/**
    5190 * Retrieve Post Thumbnail.
    5291 *
    5392 * @since 2.9.0
     
    5796 * @param string|array $attr Optional. Query string or array of attributes.
    5897 */
    5998function get_the_post_thumbnail( $post_id = null, $size = 'post-thumbnail', $attr = '' ) {
     99        if ( in_the_loop() )
     100                update_thumbnail_cache();
     101
    60102        $post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
    61103        $post_thumbnail_id = get_post_thumbnail_id( $post_id );
    62104        $size = apply_filters( 'post_thumbnail_size', $size );
    63105        if ( $post_thumbnail_id ) {
    64106                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
     107
    65108                $html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr );
    66109                do_action( 'end_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size );
    67110        } else {