diff --git a/includes/class-wc-product-variation.php b/includes/class-wc-product-variation.php index 9d68f77e20d..99fec657b14 100644 --- a/includes/class-wc-product-variation.php +++ b/includes/class-wc-product-variation.php @@ -299,6 +299,16 @@ class WC_Product_Variation extends WC_Product_Simple { $this->parent_data = $parent_data; } + /** + * Get the parent data array for this variation. + * + * @since 2.7.0 + * @return array + */ + public function get_parent_data() { + return $this->parent_data; + } + /** * Set attributes. Unlike the parent product which uses terms, variations are assigned * specific attributes using name value pairs. diff --git a/includes/data-stores/class-wc-product-variation-data-store-cpt.php b/includes/data-stores/class-wc-product-variation-data-store-cpt.php index 0de72af9df8..51ec398ed74 100644 --- a/includes/data-stores/class-wc-product-variation-data-store-cpt.php +++ b/includes/data-stores/class-wc-product-variation-data-store-cpt.php @@ -55,8 +55,10 @@ class WC_Product_Variation_Data_Store_CPT extends WC_Product_Data_Store_CPT impl throw new Exception( sprintf( 'Invalid parent for variation #%d', $product->get_id() ), 422 ); } + $product_name = get_the_title( $post_object ); + $product->set_props( array( - 'name' => get_the_title( $post_object ), + 'name' => $product_name, 'slug' => $post_object->post_name, 'date_created' => $post_object->post_date, 'date_modified' => $post_object->post_modified, @@ -69,6 +71,21 @@ class WC_Product_Variation_Data_Store_CPT extends WC_Product_Data_Store_CPT impl $this->read_extra_data( $product ); $product->set_attributes( wc_get_product_variation_attributes( $product->get_id() ) ); + /** + * Clean up old variation titles. + * The "Product #" text is intentionally not wrapped in translation functions for a faster comparision. It was not inserted as a translated string: + * https://github.com/woocommerce/woocommerce/blob/5fc88694d211e2e176bded16d7fb95cf6285249e/includes/class-wc-ajax.php#L776 + */ + if ( __( 'Variation #', 'woocommerce' ) === substr( $product_name, 0, 11 ) || ( 'Product #' . $product->get_parent_id() . ' Variation' ) === $product_name ) { + $parent_data = $product->get_parent_data(); + $new_title = $parent_data['title'] . ' – ' . wc_get_formatted_variation( $product, true, false ); + $product->set_name( $new_title ); + wp_update_post( array( + 'ID' => $product->get_id(), + 'post_title' => $new_title, + ) ); + } + // Set object_read true once all data is read. $product->set_object_read( true ); }