Skip to content

Instantly share code, notes, and snippets.

@bradyvercher
Created January 9, 2014 17:21
Show Gist options
  • Save bradyvercher/8338094 to your computer and use it in GitHub Desktop.
Save bradyvercher/8338094 to your computer and use it in GitHub Desktop.
WordPress: Cache post thumbnail attachments that appear in a WP_Query loop.
<?php
/**
* Plugin Name: Cache Post Thumbnails
* Description: Prime the post thumbnails cache for individual loops.
* Version: 1.0.0
* Author: Brady Vercher
* Author URI: http://www.blazersix.com/
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
/**
* Prime post thumbnail cache.
*
* Automatically primes the cache for the main loop on the front page and
* archives. The cache can be activated for additional queries using the
* 'blazersix_cache_post_thumbnails' filter.
*
* Custom queries can also pass a 'blazersix_cache_post_thumbnails' flag via the
* query args to prime the cache.
*
* @since 1.0.0
*
* @param array $posts List of posts in the query.
* @param WP_Query $wp_query WP Query object.
* @return array
*/
function blazersix_prime_post_thumbnails_cache( $posts, $wp_query ) {
// Prime the cache for the main front page and archive loops by default.
$is_main_archive_loop = $wp_query->is_main_query() && ! is_singular();
$do_prime_cache = apply_filters( 'blazersix_cache_post_thumbnails', $is_main_archive_loop );
if ( ! $do_prime_cache && ! $wp_query->get( 'blazersix_cache_post_thumbnails' ) ) {
return $posts;
}
update_post_thumbnail_cache( $wp_query );
return $posts;
}
add_action( 'the_posts', 'blazersix_prime_post_thumbnails_cache', 10, 2 );
@fatihsolhan
Copy link

Hello, thanks for code Bradyvercher, it works like a charm :) 🥇 But I have a problem, it doesnt caching the custom post type's thumbnails. Could you help me about that ?
Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment