How to Switch Product SKU According to the Selection of Child Products in Magento 2

Configurable products are becoming popular because they allow customers to select the exact variant they want. When purchasing a product with several options, you often need to choose from the possibilities given like size, color, or other preferences, before completing the transaction. This process differs from adding a product to the cart and making a payment, as it involves a configurable product. 

Magento provides store owners with the tools to create and sell configurable products through its backend. Setting up a configurable product requires defining various options like size, color, and model as Magento treats each variant as an individual product. Each variation has its own SKU and inventory system.

On the frontend, when a user selects a specific option for a configurable product, the options and price will adjust accordingly. However, the SKU does not change in Magento’s store environment. 

In this guide, we’ll learn how to switch product SKUs according to the selection of child products in Magento 2.

8 Steps to Implement the SKUs in Magento 2

To dynamically change the SKU on the Product Detail Page (PDP) when the customer selects different color or size options in Magento 2, you need to use the below code to update the SKU based on the selected options.

Here’s a step-by-step guide on how to implement this functionality:

Step 1: Create the Module Registration File

You need to register your custom module using registration.php.

Path: app/code/Klizer/ChangeSkuDynamically/registration.php

Purpose: This file registers your custom module with Magento. The ComponentRegistrar ensures that Magento recognizes the module so it can be executed.

<?php
/**
 * Klizer
 *
 * @category  Klizer
 * @package   Klizer_ChangeSkuDynamically
 * @copyright Copyright © 2024 Klizer. All rights reserved.
 * @author    Klizer - info@klizer.com
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Klizer_ChangeSkuDynamically',
    __DIR__
);

Step 2: Define the Module in module.xml

Path: app/code/Klizer/ChangeSkuDynamically/etc/module.xml

Purpose: This file declares the module’s version and defines the module’s name. Magento reads this configuration to know when and how to initialize your module.

<?xml version="1.0"?>
<!--
/**
 * Klizer
 *
 * @category  Klizer
 * @package   Klizer_ChangeSkuDynamically
 * @copyright Copyright © 2024 Klizer. All rights reserved.
 * @author    Klizer - info@klizer.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Klizer_ChangeSkuDynamically" setup_version="1.0.0">
    </module>
</config>

Step 3: Create a Plugin For Configurable Product

Path: app/code/Klizer/ChangeSkuDynamically/etc/di.xml

Purpose: This dependency injection (DI) file defines a plugin. The plugin intercepts the ConfigurableProduct block’s method and modifies its behavior. The plugin is specified in a sort order, giving it priority.

<?xml version="1.0"?>
<!--
/**
 * Klizer
 *
 * @category  Klizer
 * @package   Klizer_ChangeSkuDynamically
 * @copyright Copyright © 2024 Klizer. All rights reserved.
 * @author    Klizer - info@klizer.com
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable">
        <plugin name="change_sku_when_product_variant_change" type="Klizer\ChangeSkuDynamically\Plugin\ConfigurableProduct" sortOrder="10" />
    </type>
</config>

Step 4: Create Plugin Class

Path: app/code/Klizer/ChangeSkuDynamically/Plugin/ConfigurableProduct.php

Purpose: This is the actual plugin logic. It hooks into the getJsonConfig method of the configurable product block. This code manipulates the product’s JSON configuration to include SKU switching logic. The SKUs of the parent and child products are available for switching on the frontend.

<?php

/**
 * Klizer
 *
 * @category  Klizer
 * @package   Klizer_ChangeSkuDynamically
 * @copyright Copyright © 2024 Klizer. All rights reserved.
 * @author    Klizer - info@klizer.com
 */

declare(strict_types=1);

namespace Klizer\ChangeSkuDynamically\Plugin;

use Magento\ConfigurableProduct\Block\Product\View\Type\Configurable;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Serialize\Serializer\Json as JsonSerializer;
use Magento\Store\Model\ScopeInterface;

class ConfigurableProduct
{
    public const GENERAL_SKU_SELECTOR = '.product.attribute.sku .value'; //here you can change SKU Selector.
    public const PRODUCT_VIEW = 'catalog_product_view';

    /**
     * @var JsonSerializer
     */
    private JsonSerializer $jsonSerializer;

    /**
     * @var HttpRequest
     */
    private HttpRequest $httpRequest;

    /**
     * @var ScopeConfigInterface
     */
    private ScopeConfigInterface $scopeConfig;

    /**
     * @param JsonSerializer $jsonSerializer
     * @param HttpRequest $httpRequest
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        JsonSerializer $jsonSerializer,
        HttpRequest $httpRequest,
        ScopeConfigInterface $scopeConfig
    ) {
        $this->jsonSerializer = $jsonSerializer;
        $this->httpRequest = $httpRequest;
        $this->scopeConfig = $scopeConfig;
    }

    /**
 * Add a config to switch SKU
     *
     * @param Configurable $subject
     * @param string $result
     * @return string
     */
    public function afterGetJsonConfig(Configurable $subject, string $result): string
    {
        $jsonConfig = (array)$this->jsonSerializer->unserialize($result);
        $moduleConfig = &$jsonConfig['klizer_changeskudynamically'];
        $moduleConfig['data']['full_action_name'] = $this->httpRequest->getFullActionName();
        $moduleConfig['general']['switch_sku_status'] = true; //here you can add enable/disable condition.

        if ($moduleConfig['data']['full_action_name'] === self::PRODUCT_VIEW
            && $moduleConfig['general']['switch_sku_status']) {
            $moduleConfig['general']['sku_selector'] = self::GENERAL_SKU_SELECTOR;
            $parentProduct = $subject->getProduct();
            $moduleConfig['data']['skus']['parent'][$parentProduct->getId()] = $parentProduct->getSku();

            foreach ($subject->getAllowProducts() as $child) {
                $moduleConfig['data']['skus'][$child->getId()] = $child->getSku();
            }
        }

        return $this->jsonSerializer->serialize($jsonConfig);
    }
}

Step 5: RequireJS Configuration

Path: app/code/Klizer/ChangeSkuDynamically/view/frontend/requirejs-config.js

Purpose: This file configures RequireJS mixins, allowing you to extend or override default Magento JS modules. It integrates your custom JS logic with existing Magento modules like configurable and swatch-renderer.

var config = {
    config: {
        mixins: {
            'Magento_ConfigurableProduct/js/configurable': {
                'Klizer_ChangeSkuDynamically/js/configurable': true
            },
            'Magento_Swatches/js/swatch-renderer': {
                'Klizer_ChangeSkuDynamically/js/swatch-renderer': true
            }
        }
    }
};

Step 6: Create JS Switcher File

Path: app/code/Klizer/ChangeSkuDynamically/view/frontend/web/js/switcher.js

Purpose: This JavaScript file manages the SKU switch when a customer selects a product option on the frontend. It selects the corresponding SKU from the config and dynamically updates the product’s displayed SKU.

define(['jquery'], function ($) {
    'use strict';
    return {
        switch: function (config, productId) {
            var moduleConfig = config['klizer_changeskudynamically'];
            if (productId !== undefined && moduleConfig['general']['switch_sku_status'] === true &&
                moduleConfig['data']['full_action_name'] === 'catalog_product_view') {
                $(moduleConfig['general']['sku_selector']).html(moduleConfig['data']['skus'][productId]);
            }
        }
    };
});

Step 7: Extend the Swatch Renderer

Path: app/code/Klizer/ChangeSkuDynamically/view/frontend/web/js/swatch-renderer.jsPurpose: This JavaScript file extends Magento’s swatch renderer to call the SKU switcher whenever a new product variation is selected. It hooks into the _UpdatePrice function to switch SKUs when the price is updated.

define([
    'jquery',
    'Klizer_ChangeSkuDynamically/js/switcher'
], function ($, switcher) {
    'use strict';
    return function (widget) {
        $.widget('mage.SwatchRenderer', widget, {
            _UpdatePrice: function () {
                switcher.switch(this.options.jsonConfig, this.getProduct());
                this._super();
            }
        });
        return $.mage.SwatchRenderer;
    };
});

Step 8: Extend Configurable Product Logic

Path: app/code/Klizer/ChangeSkuDynamically/view/frontend/web/js/configurable.js

Purpose: This JS file extends Magento’s configurable product logic to execute the SKU switcher when the price reloads. It calls the SKU switching logic right before the price is reloaded.

define([
    'jquery',
    'Klizer_ChangeSkuDynamically/js/switcher'
], function ($, switcher) {
    'use strict';
    return function (widget) {
        $.widget('mage.configurable', widget, {
            _reloadPrice: function () {
                switcher.switch(this.options.spConfig, this.simpleProduct);
                this._super();
            }
        });

        return $.mage.configurable;
    };
});

Switch SKU Based on Child Product Selection in Magento 2 with Klizer 

Magento 2 doesn’t provide an out-of-the-box solution to change the SKU based on product variant changes. But with the above-mentioned custom code, you can create a solution to modify the SKU as needed.

If you’re unable to implement this manually or need help (expert guide) customizing it further, feel free to reach out to Adobe Commerce (Magento) solution partners. Our team can assist you with tailored solutions for your Magento needs.

About The Author

Discover What You’re Missing

Get in touch with us for expert consultation