I want to make swatches in sorting in natural sorting order. Like using below PHP function: "strnatcasecmp"

I know it can be done through admin like drag and drop to size/color option. But I only want this done by programmatically as no matter what is the position set in the admin for these options.

Below is the file where these swatches are rendering:


Below is the screenshot is attached: enter image description here

1 Answer 1


You can override /vendor/magento/module-swatches/Block/Product/Renderer/Configurable.php file in your custom module for customisation in swatches.

You need to change in public function getJsonSwatchConfig() function for sort text swatches.


public function getJsonSwatchConfig()
    $attributesData = $this->getSwatchAttributesData();
    $allOptionIds = $this->getConfigurableOptionsIds($attributesData);
    $swatchesData = $this->swatchHelper->getSwatchesByOptionsId($allOptionIds);

    $config = [];
    foreach ($attributesData as $attributeId => $attributeDataArray) {
        if (isset($attributeDataArray['options'])) {
            $config[$attributeId] = $this->addSwatchDataForAttribute(
    return $this->jsonEncoder->encode($config);

You just simply check for text swatches in getJsonSwatchConfig():

if ($attributeDataArray['swatch_input_type'] == 'text') {
//Your custom code

I hope it will helpful for you.

  • can you pls show me how can I sort it as I have already tried this way, also the $config has valid data as I want, but on product page, its not working. Feb 24, 2020 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.