_prime_post_parent_id_caches()WP 6.4.0

Prime the cache containing the parent ID of various post objects.

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

No Hooks.

Returns

null. Nothing (null).

Usage

_prime_post_parent_id_caches( $ids );
$ids(int[]) (required)
ID list.

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 6.4.0 Introduced.

_prime_post_parent_id_caches() code WP 6.8.1

function _prime_post_parent_id_caches( array $ids ) {
	global $wpdb;

	$ids = array_filter( $ids, '_validate_cache_id' );
	$ids = array_unique( array_map( 'intval', $ids ), SORT_NUMERIC );

	if ( empty( $ids ) ) {
		return;
	}

	$cache_keys = array();
	foreach ( $ids as $id ) {
		$cache_keys[ $id ] = 'post_parent:' . (string) $id;
	}

	$cached_data = wp_cache_get_multiple( array_values( $cache_keys ), 'posts' );

	$non_cached_ids = array();
	foreach ( $cache_keys as $id => $cache_key ) {
		if ( false === $cached_data[ $cache_key ] ) {
			$non_cached_ids[] = $id;
		}
	}

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

		if ( $fresh_posts ) {
			$post_parent_data = array();
			foreach ( $fresh_posts as $fresh_post ) {
				$post_parent_data[ 'post_parent:' . (string) $fresh_post->ID ] = (int) $fresh_post->post_parent;
			}

			wp_cache_add_multiple( $post_parent_data, 'posts' );
		}
	}
}