{ $thumbnail_id = (int) get_post_meta( $variation_id, '_thumbnail_id', true ); if ( $thumbnail_id > 0 ) { $image_id = $thumbnail_id; } } wp_cache_set( $cache_key, $image_id, 'products' ); return $image_id; } private function get_best_match_variation_permalink( int $product_id, array $query_items ) { $cache_key = WC_Cache_Helper::get_cache_prefix( 'product_' . $product_id ) . '_variation_permalink_' . md5( wp_json_encode( $query_items ) ); $permalink = wp_cache_get( $cache_key, 'products' ); if ( $permalink !== false ) { return $permalink; } $permalink = ''; $variation_id = $this->get_best_match_variation_id( $product_id, $query_items ); if ( $variation_id > 0 ) { $new_permalink = get_permalink( $variation_id ); if ( ! empty( $new_permalink ) ) { $permalink = $new_permalink; } } wp_cache_set( $cache_key, $permalink, 'products' ); return $permalink; } private function get_best_match_variation_id( int $product_id, array $query_items ): int { $cache_key = WC_Cache_Helper::get_cache_prefix( 'product_' . $product_id ) . '_variation_id_' . md5( wp_json_encode( $query_items ) ); $variation_id = wp_cache_get( $cache_key, 'products' ); if ( $variation_id !== false ) { return intval( $variation_id ); } $variation_id = 0; if ( empty( $query_items ) ) { return $variation_id; } $product = wc_get_product( $product_id ); if ( $product->get_type() !== 'variable' ) { return $variation_id; } $user_attributes_converted = []; foreach ( $query_items as $attribute => $values ) { $source = $this->store_filters->get_filter_prop_by_other_prop_value( 'source', 'url_slug', $attribute ); if ( empty( $source ) ) { continue; } $source_obj = $this->filter_sources->get_source( $source ); if ( $source_obj->get_data_attr( 'sourceType' ) === 'taxonomy' ) { $raw_value = $source_obj->get_data_attr( 'rawValue' ); $user_attributes_converted[ $raw_value ] = $values; } } $match_attributes = []; foreach ( $product->get_attributes() as $attribute ) { if ( ! $attribute->get_variation() ) { continue; } $attribute_name = $attribute->get_name(); if ( array_key_exists( $attribute_name, $user_attributes_converted ) ) { $match_attributes[ wc_variation_attribute_name( $attribute_name ) ] = $user_attributes_converted[ $attribute_name ]; } } $args = [ 'post_parent' => $product_id, 'post_type' => 'product_variation', 'meta_query' => [ 'relation' => 'AND', ], 'orderby' => 'ID', 'order' => 'ASC', 'posts_per_page' => 1, 'fields' => 'ids', ]; foreach ( $match_attributes as $key => $values ) { $sub = [ 'relation' => 'OR', ]; foreach ( $values as $value ) { $sub[] = [ 'key' => $key, 'value' => $value, 'compare' => '=', ]; } $args['meta_query'][] = $sub; } $query = new WP_Query( $args ); if ( $query->have_posts() ) { $variation_id = intval( $query->posts[0] ); } wp_cache_set( $cache_key, $variation_id, 'products' ); return $variation_id; } }