diff --git a/includes/shortcodes/class-wc-shortcode-products.php b/includes/shortcodes/class-wc-shortcode-products.php index 5df396ec336..5fb33ffb4fe 100644 --- a/includes/shortcodes/class-wc-shortcode-products.php +++ b/includes/shortcodes/class-wc-shortcode-products.php @@ -429,6 +429,26 @@ class WC_Shortcode_Products { return $classes; } + /** + * Generate and return the transient name for this shortcode based on the query args. + * + * @since 3.3.0 + * @return string + */ + protected function get_transient_name() { + $transient_name = 'wc_loop' . substr( md5( wp_json_encode( $this->query_args ) . $this->type ), 28 ); + + if ( 'rand' === $this->query_args['orderby'] ) { + // When using rand, we'll cache a number of random queries and pull those to avoid querying rand on each page load. + $rand_index = rand( 0, max( 1, absint( apply_filters( 'woocommerce_product_query_max_rand_cache_count', 5 ) ) ) ); + $transient_name .= $rand_index; + } + + $transient_name .= WC_Cache_Helper::get_transient_version( 'product_query' ); + + return $transient_name; + } + /** * Get products. * @@ -436,7 +456,7 @@ class WC_Shortcode_Products { * @return WP_Query */ protected function get_products() { - $transient_name = 'wc_loop' . substr( md5( wp_json_encode( $this->query_args ) . $this->type ), 28 ) . WC_Cache_Helper::get_transient_version( 'product_query' ); + $transient_name = $this->get_transient_name(); $products = get_transient( $transient_name ); if ( false === $products || ! is_a( $products, 'WP_Query' ) ) {