Abstract_WC_Order_Data_Store_CPT::prime_order_item_caches_for_orders()protectedWC 1.0

Prime following caches:

  1. item-$order_item_id For individual items.
  2. order-items-$order-id For fetching items associated with an order.
  3. order-item meta.

Method of the class: Abstract_WC_Order_Data_Store_CPT{}

No Hooks.

Return

null. Nothing (null).

Usage

// protected - for code of main (parent) or child class
$result = $this->prime_order_item_caches_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.

Abstract_WC_Order_Data_Store_CPT::prime_order_item_caches_for_orders() code WC 9.4.2

protected function prime_order_item_caches_for_orders( $order_ids, $query_vars ) {
	global $wpdb;
	if ( isset( $query_vars['fields'] ) && 'all' !== $query_vars['fields'] ) {
		$line_items = array(
			'line_items',
			'shipping_lines',
			'fee_lines',
			'coupon_lines',
		);

		if ( is_array( $query_vars['fields'] ) && 0 === count( array_intersect( $line_items, $query_vars['fields'] ) ) ) {
			return;
		}
	}
	$cache_keys     = array_map(
		function ( $order_id ) {
			return 'order-items-' . $order_id;
		},
		$order_ids
	);
	$cache_values   = wc_cache_get_multiple( $cache_keys, 'orders' );
	$non_cached_ids = array();
	foreach ( $order_ids as $order_id ) {
		if ( false === $cache_values[ 'order-items-' . $order_id ] ) {
			$non_cached_ids[] = $order_id;
		}
	}
	if ( empty( $non_cached_ids ) ) {
		return;
	}

	$non_cached_ids        = esc_sql( $non_cached_ids );
	$non_cached_ids_string = implode( ',', $non_cached_ids );
	$order_items           = $wpdb->get_results(
	// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		"SELECT order_item_type, order_item_id, order_id, order_item_name FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id in ( $non_cached_ids_string ) ORDER BY order_item_id;"
	);
	if ( empty( $order_items ) ) {
		return;
	}

	$order_items_for_all_orders = array_reduce(
		$order_items,
		function ( $order_items_collection, $order_item ) {
			if ( ! isset( $order_items_collection[ $order_item->order_id ] ) ) {
				$order_items_collection[ $order_item->order_id ] = array();
			}
			$order_items_collection[ $order_item->order_id ][] = $order_item;
			return $order_items_collection;
		}
	);
	foreach ( $order_items_for_all_orders as $order_id => $items ) {
		wp_cache_set( 'order-items-' . $order_id, $items, 'orders' );
	}
	foreach ( $order_items as $item ) {
		wp_cache_set( 'item-' . $item->order_item_id, $item, 'order-items' );
	}
	$order_item_ids = wp_list_pluck( $order_items, 'order_item_id' );
	update_meta_cache( 'order_item', $order_item_ids );
}