WC_Order_Data_Store_CPT::prime_raw_meta_cache_for_orders()privateWC 1.0

Prime cache for raw meta data for orders in bulk. Difference between this and WP built-in metadata is that this method also fetches meta_id field which we use and cache it.

Method of the class: WC_Order_Data_Store_CPT{}

No Hooks.

Return

null. Nothing (null).

Usage

// private - for code of main (parent) class only
$result = $this->prime_raw_meta_cache_for_orders( $order_ids, $query_vars );
$order_ids(array) (required)
Order Ids to prime cache for.
$query_vars(array) (required)
Query vars for the query.

WC_Order_Data_Store_CPT::prime_raw_meta_cache_for_orders() code WC 8.7.0

private function prime_raw_meta_cache_for_orders( $order_ids, $query_vars ) {
	global $wpdb;

	if ( isset( $query_vars['fields'] ) && 'all' !== $query_vars['fields'] ) {
		if ( is_array( $query_vars['fields'] ) && ! in_array( 'meta_data', $query_vars['fields'], true ) ) {
			return;
		}
	}

	$cache_keys_mapping = array();
	foreach ( $order_ids as $order_id ) {
		$cache_keys_mapping[ $order_id ] = WC_Order::generate_meta_cache_key( $order_id, 'orders' );
	}
	$cache_values   = wc_cache_get_multiple( array_values( $cache_keys_mapping ), 'orders' );
	$non_cached_ids = array();
	foreach ( $order_ids as $order_id ) {
		if ( false === $cache_values[ $cache_keys_mapping[ $order_id ] ] ) {
			$non_cached_ids[] = $order_id;
		}
	}
	if ( empty( $non_cached_ids ) ) {
		return;
	}
	$order_ids           = esc_sql( $non_cached_ids );
	$order_ids_in        = "'" . implode( "', '", $order_ids ) . "'";
	$raw_meta_data_array = $wpdb->get_results(
	// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		"SELECT post_id as object_id, meta_id, meta_key, meta_value
			FROM {$wpdb->postmeta}
			WHERE post_id IN ( $order_ids_in )
			ORDER BY post_id"
	// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	);
	$raw_meta_data_collection = array_reduce(
		$raw_meta_data_array,
		function ( $collection, $raw_meta_data ) {
			if ( ! isset( $collection[ $raw_meta_data->object_id ] ) ) {
				$collection[ $raw_meta_data->object_id ] = array();
			}
			$collection[ $raw_meta_data->object_id ][] = $raw_meta_data;
			return $collection;
		},
		array()
	);
	WC_Order::prime_raw_meta_data_cache( $raw_meta_data_collection, 'orders' );
}