Abstract_WC_Order_Data_Store_CPT::prime_refund_caches_for_orders │ protected │ WC 10.7.0

Prime refund cache for a batch of orders.

WC_Order::get_refunds() checks wp_cache before querying. By fetching all refunds for the batch in a single query and populating the cache, we eliminate one query per order.

Method of the class: Abstract_WC_Order_Data_Store_CPT{}

No Hooks.

Returns

void. Nothing (null).

Usage

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

Changelog

Since 10.7.0 Introduced.

Abstract_WC_Order_Data_Store_CPT::prime_refund_caches_for_orders() code WC 11.1.2

protected function prime_refund_caches_for_orders( $order_ids, $query_vars ) {
	if ( isset( $query_vars['fields'] ) && 'all' !== $query_vars['fields'] ) {
		if ( is_array( $query_vars['fields'] ) && ! in_array( 'refunds', $query_vars['fields'], true ) ) {
			return;
		}
	}

	$cache_keys_mapping = array();
	foreach ( $order_ids as $order_id ) {
		$cache_keys_mapping[ $order_id ] = WC_Cache_Helper::get_cache_prefix( 'orders' ) . 'refund_ids' . $order_id;
	}

	$non_cached_ids = array();
	$cache_values   = wc_cache_get_multiple( array_values( $cache_keys_mapping ), 'orders' );

	if ( ! is_array( $cache_values ) ) {
		$non_cached_ids = $order_ids;
	} else {
		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;
	}

	/**
	 * Fetch all refunds for the given order IDs.
	 *
	 * @var WC_Order_Refund[] $refunds
	 */
	$refunds = wc_get_orders(
		array(
			'type'            => 'shop_order_refund',
			'post_parent__in' => $non_cached_ids,
			'limit'           => -1,
		)
	);

	$order_refund_ids = array_fill_keys( $non_cached_ids, array() );
	foreach ( $refunds as $refund ) {
		if ( $refund instanceof \WC_Order_Refund && isset( $order_refund_ids[ $refund->get_parent_id() ] ) ) {
			$order_refund_ids[ $refund->get_parent_id() ][] = $refund->get_id();
		}
	}

	foreach ( $non_cached_ids as $order_id ) {
		wp_cache_set( $cache_keys_mapping[ $order_id ], $order_refund_ids[ $order_id ], 'orders' );
	}
}