Magento – Magento 2: How to change sku dynamically in configurable product view page

configurable-productmagento2productproduct-view

The configurable product based on variation product images are changing, but not SKU, is there any way to change SKU also?

Best Answer

You have to override function getAllSizeImages() from Magento\Swatches\Helper\Data.php file.

 protected function getAllSizeImages(Product $product, $imageFile)
    {
        return [
            'large' => $this->imageHelper->init($product, 'product_page_image_large')
                ->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)
                ->setImageFile($imageFile)
                ->getUrl(),
            'medium' => $this->imageHelper->init($product, 'product_page_image_medium')
                ->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)
                ->setImageFile($imageFile)
                ->getUrl(),
            'small' => $this->imageHelper->init($product, 'product_page_image_small')
                ->setImageFile($imageFile)
                ->getUrl(),
            'sku' => $product->getSku()
        ];
    }

After change variant of product you have got response with sku of variant and you can change sku based on response using js.