From a3f14c7256f7b638f853894266926e72b55e4847 Mon Sep 17 00:00:00 2001 From: Rodrigo Primo Date: Wed, 11 Oct 2017 14:49:10 -0300 Subject: [PATCH] Caches call to load product variation attributes This commit adds product variation attributes to WP cache when they are first loaded to avoid running the same database queries when the same product is loaded multiple times. This cache will be invalidated whenever product attributes are changed. Fixes #17120 --- .../class-wc-product-variable-data-store-cpt.php | 9 +++++++++ includes/wc-product-functions.php | 13 +++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/includes/data-stores/class-wc-product-variable-data-store-cpt.php b/includes/data-stores/class-wc-product-variable-data-store-cpt.php index 10135b5ad91..6a2c2a29292 100644 --- a/includes/data-stores/class-wc-product-variable-data-store-cpt.php +++ b/includes/data-stores/class-wc-product-variable-data-store-cpt.php @@ -98,6 +98,13 @@ class WC_Product_Variable_Data_Store_CPT extends WC_Product_Data_Store_CPT imple $variation_attributes = array(); $attributes = $product->get_attributes(); $child_ids = $product->get_children(); + $cache_key = WC_Cache_Helper::get_cache_prefix( 'products' ) . 'product_variation_attributes_' . $product->get_id(); + $cache_group = 'products'; + $cached_data = wp_cache_get( $cache_key, $cache_group ); + + if ( false !== $cached_data ) { + return $cached_data; + } if ( ! empty( $child_ids ) && ! empty( $attributes ) ) { foreach ( $attributes as $attribute ) { @@ -140,6 +147,8 @@ class WC_Product_Variable_Data_Store_CPT extends WC_Product_Data_Store_CPT imple } } + wp_cache_set( $cache_key, $variation_attributes, $cache_group ); + return $variation_attributes; } diff --git a/includes/wc-product-functions.php b/includes/wc-product-functions.php index 69348c280f4..802be38113e 100644 --- a/includes/wc-product-functions.php +++ b/includes/wc-product-functions.php @@ -126,8 +126,17 @@ function wc_delete_product_transients( $post_id = 0 ) { // Does this product have a parent? $product = wc_get_product( $post_id ); - if ( $product && $product->get_parent_id() > 0 ) { - wc_delete_product_transients( $product->get_parent_id() ); + if ( $product ) { + if ( $product->get_parent_id() > 0 ) { + wc_delete_product_transients( $product->get_parent_id() ); + } + + if ( 'variable' === $product->get_type() ) { + wp_cache_delete( + WC_Cache_Helper::get_cache_prefix( 'products' ) . 'product_variation_attributes_' . $product->get_id(), + 'products' + ); + } } }