函数文档

update_post_thumbnail_cache()

💡 云策文档标注

概述

update_post_thumbnail_cache() 函数用于更新当前循环中文章缩略图的缓存,以提高性能。它通过预缓存文章和缩略图数据,减少数据库查询。

关键要点

  • 函数接受一个可选的 WP_Query 实例参数,默认为全局 $wp_query。
  • 如果缩略图已缓存(通过 $wp_query->thumbnails_cached 检查),函数会直接返回。
  • 函数首先缓存父文章对象,然后收集并缓存所有缩略图的 ID。
  • 这有助于避免在调用 get_the_post_thumbnail() 时触发额外的数据库查询。

代码示例

function update_post_thumbnail_cache( $wp_query = null ) {
	if ( ! $wp_query ) {
		$wp_query = $GLOBALS['wp_query'];
	}

	if ( $wp_query->thumbnails_cached ) {
		return;
	}

	$thumb_ids = array();

	/*
	 * $wp_query may contain an array of post objects or post IDs.
	 *
	 * This ensures the cache is primed for all post objects to avoid
	 * `get_post()` calls in `get_the_post_thumbnail()` triggering an
	 * additional database call for each post.
	 */
	$parent_post_ids = array();
	foreach ( $wp_query->posts as $post ) {
		if ( $post instanceof WP_Post ) {
			$parent_post_ids[] = $post->ID;
		} elseif ( is_int( $post ) ) {
			$parent_post_ids[] = $post;
		}
	}
	_prime_post_caches( $parent_post_ids, false, true );

	foreach ( $wp_query->posts as $post ) {
		$id = get_post_thumbnail_id( $post );
		if ( $id ) {
			$thumb_ids[] = $id;
		}
	}

	if ( ! empty( $thumb_ids ) ) {
		_prime_post_caches( $thumb_ids, false, true );
	}

	$wp_query->thumbnails_cached = true;
}

注意事项

  • 函数自 WordPress 3.2.0 版本引入。
  • 相关函数包括 get_post_thumbnail_id() 和 _prime_post_caches()。
  • 被 WP_REST_Posts_Controller::get_items() 和 WP_Media_List_Table::prepare_items() 等使用。

📄 原文内容

Updates cache for thumbnails in the current loop.

Parameters

$wp_queryWP_Query|nulloptional
A WP_Query instance. Defaults to the $wp_query global.

Default:null

Source

function update_post_thumbnail_cache( $wp_query = null ) {
	if ( ! $wp_query ) {
		$wp_query = $GLOBALS['wp_query'];
	}

	if ( $wp_query->thumbnails_cached ) {
		return;
	}

	$thumb_ids = array();

	/*
	 * $wp_query may contain an array of post objects or post IDs.
	 *
	 * This ensures the cache is primed for all post objects to avoid
	 * `get_post()` calls in `get_the_post_thumbnail()` triggering an
	 * additional database call for each post.
	 */
	$parent_post_ids = array();
	foreach ( $wp_query->posts as $post ) {
		if ( $post instanceof WP_Post ) {
			$parent_post_ids[] = $post->ID;
		} elseif ( is_int( $post ) ) {
			$parent_post_ids[] = $post;
		}
	}
	_prime_post_caches( $parent_post_ids, false, true );

	foreach ( $wp_query->posts as $post ) {
		$id = get_post_thumbnail_id( $post );
		if ( $id ) {
			$thumb_ids[] = $id;
		}
	}

	if ( ! empty( $thumb_ids ) ) {
		_prime_post_caches( $thumb_ids, false, true );
	}

	$wp_query->thumbnails_cached = true;
}

Changelog

Version Description
3.2.0 Introduced.