Magento – Display Child Product SKU in Product Page

configurable-productmagento2sku

I am using Magento 2. I would like to display child product SKU in Main product page while user clicks on configurable Swatches.

I am trying to gather information from below file.

public_html\vendor\magento\module-swatches\view\frontend\templates\product\view\renderer.phtml

like below

<div class="swatch-opt"></div>
<script>
    require(["jquery", "jquery/ui", "swatchRenderer"], function ($) {
        $('.swatch-opt').SwatchRenderer({
            jsonConfig: <?php /* @escapeNotVerified */ echo $swatchOptions = $block->getJsonConfig(); ?>,
            jsonSwatchConfig: <?php /* @escapeNotVerified */ echo $swatchOptions = $block->getJsonSwatchConfig(); ?>,
            mediaCallback: '<?php /* @escapeNotVerified */ echo $block->getMediaCallback() ?>'

        });
    });

    console.log('<?php echo $block->getJsonSwatchConfig(); ?>');
</script>

I am getting below output in console.

{"90":{"12":{"type":"1","value":"#474747","label":"Black"},"13":{"type":"1","value":"#45bcf8","label":"Blue"},"20":{"type":"1","value":"#da859c","label":"Pink"},"21":{"type":"1","value":"#a15ebb","label":"Purple"},"22":{"type":"1","value":"#cb5d4a","label":"Red"}}}

But I could not find SKU there. I would like to get SKU to display that in Main product Page.

Best Answer

If you use version 2.1.9 and below. open file vendor/magento/module-swatches/Helper/Data.php find private function getAllSizeImages(ModelProduct $product, $imageFile) add:

'sku' => $product->getSku()

all function code looke like:

private function getAllSizeImages(ModelProduct $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(),
 ];}

well be callback SKU.

more information: https://forum.magentochina.org/t/sku/33