Automattic\WooCommerce\Blocks\BlockTypes
AbstractProductGrid::prime_product_variations()
Prime query cache of product variation meta data.
Prepares values in the product_ID_variation_meta_data cache for later use in the ProductSchema::get_variations() method. Doing so here reduces the total number of queries needed.
Method of the class: AbstractProductGrid{}
No Hooks.
Return
null
. Nothing (null).
Usage
// protected - for code of main (parent) or child class $result = $this->prime_product_variations( $product_ids );
- $product_ids(int[]) (required)
- Product ids to prime variation cache for.
AbstractProductGrid::prime_product_variations() AbstractProductGrid::prime product variations code WC 9.4.2
protected function prime_product_variations( $product_ids ) { $cache_group = 'product_variation_meta_data'; $prime_product_ids = $this->get_non_cached_ids( wp_parse_id_list( $product_ids ), $cache_group ); if ( ! $prime_product_ids ) { return; } global $wpdb; // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared $product_variations = $wpdb->get_results( "SELECT ID as variation_id, post_parent as product_id from {$wpdb->posts} WHERE post_parent IN ( " . implode( ',', $prime_product_ids ) . ' )', ARRAY_A ); $prime_variation_ids = array_column( $product_variations, 'variation_id' ); $variation_ids_by_parent = array_column( $product_variations, 'product_id', 'variation_id' ); if ( empty( $prime_variation_ids ) ) { return; } $all_variation_meta_data = $wpdb->get_results( $wpdb->prepare( "SELECT post_id as variation_id, meta_key as attribute_key, meta_value as attribute_value FROM {$wpdb->postmeta} WHERE post_id IN (" . implode( ',', array_map( 'esc_sql', $prime_variation_ids ) ) . ') AND meta_key LIKE %s', $wpdb->esc_like( 'attribute_' ) . '%' ) ); // phpcs:enable // Prepare the data to cache by indexing by the parent product. $primed_data = array_reduce( $all_variation_meta_data, function( $values, $data ) use ( $variation_ids_by_parent ) { $values[ $variation_ids_by_parent[ $data->variation_id ] ?? 0 ][] = $data; return $values; }, array_fill_keys( $prime_product_ids, [] ) ); // Cache everything. foreach ( $primed_data as $product_id => $variation_meta_data ) { wp_cache_set( $product_id, [ 'last_modified' => get_the_modified_date( 'U', $product_id ), 'data' => $variation_meta_data, ], $cache_group ); } }