_prime_post_caches()WP 3.4.0

Adds any posts from the given IDs to the cache that do not already exist in cache

Internal function — this function is designed to be used by the kernel itself. It is not recommended to use this function in your code.

1 time — 0.012805 sec (extremely slow) | 50000 times — 0.78 sec (very fast)

No Hooks.

Return

null. Nothing (null).

Usage

_prime_post_caches( $ids, $update_term_cache, $update_meta_cache );
$ids(int[]) (required)
ID list.
$update_term_cache(true|false)
Whether to update the term cache.
Default: true
$update_meta_cache(true|false)
Whether to update the meta cache.
Default: true

Examples

0

#1 Add the posts to the cache when processing comments

An example from the core function get_comments().

// Prime comment post caches.
if ( $this->query_vars['update_comment_post_cache'] ) {

	$comment_post_ids = array();

	foreach ( $_comments as $_comment ) {
		$comment_post_ids[] = $_comment->comment_post_ID;
	}

	_prime_post_caches( $comment_post_ids, false, false );
}
0

#2 Add the posts to the cache when we get the posts

An example from the core function get_posts().

$ids = $wpdb->get_col( $this->request );

if ( $ids ) {
	$this->posts = $ids;
	$this->set_found_posts( $q, $limits );
	_prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
} else {
	$this->posts = array();
}

Notes

Changelog

Since 3.4.0 Introduced.
Since 6.1.0 This function is no longer marked as "private".

_prime_post_caches() code WP 6.5.2

function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
	global $wpdb;

	$non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
	if ( ! empty( $non_cached_ids ) ) {
		$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );

		if ( $fresh_posts ) {
			// Despite the name, update_post_cache() expects an array rather than a single post.
			update_post_cache( $fresh_posts );
		}
	}

	if ( $update_meta_cache ) {
		update_postmeta_cache( $ids );
	}

	if ( $update_term_cache ) {
		$post_types = array_map( 'get_post_type', $ids );
		$post_types = array_unique( $post_types );
		update_object_term_cache( $ids, $post_types );
	}
}