---
title: "How to Create Custom Swatch Attribute Programmatically in Magento 2?"
url: "https://magecomp.com/blog/create-custom-swatch-attribute-programmatically-magento-2/"
date: "2022-11-21T15:27:05+00:00"
modified: "2025-02-13T11:53:30+00:00"
author:
  name: "Dhiren Vasoya"
  url: "https://magecomp.com/"
categories:
  - "How To"
  - "Magento 2"
word_count: 496
reading_time: "3 min read"
summary: "Hello Magento Friends,"
description: "Learn How to Create Custom Swatch Attribute Programmatically in Magento 2."
keywords: "How To, Magento 2"
language: "en"
schema_type: "Article"
related_posts:
  - title: "How to Get List of Active Payment Methods Using Command Line?"
    url: "https://magecomp.com/blog/get-list-of-active-payment-methods-using-command-line-in-magento-2/"
  - title: "Magento 2: How to Send Email when Product Price Change"
    url: "https://magecomp.com/blog/magento-2-send-email-when-product-price-change/"
  - title: "How to Create Admin User via Command Line in Magento 2?"
    url: "https://magecomp.com/blog/create-admin-user-via-command-line-magento-2/"
---

# How to Create Custom Swatch Attribute Programmatically in Magento 2?

_Published: November 21, 2022_  
_Author: Dhiren Vasoya_  

![How to Create Custom Swatch Attribute Programmatically in Magento 2](https://magecomp.com/blog/wp-content/uploads/2022/11/How-to-Create-Custom-Swatch-Attribute-Programmatically-in-Magento-2-1024x512.webp)

**Hello Magento Friends,**

In today’s blog, I will explain How to Create Custom Swatch Attribute Programmatically in Magento 2?
[![hyva theme development](https://magecomp.com/blog/wp-content/uploads/2025/02/hyva-theme-development-CTA-6.webp)](https://magecomp.com/services/hyva-theme-development/)

There are many types of attributes like price, text, swatch, drop-down, etc in Magento 2. Swatch attributes are used in the product page, product listings, and layered navigation. One can also [**create product-wise swatches in Magento 2**](https://magecomp.com/blog/set-product-wise-swatches-magento-2/). Swatches help to increase the shopping experience of customers by providing options to select from.
Here we will learn about Creating Custom Swatch Attribute Programmatically in Magento 2.
## Steps to Create Custom Swatch Attribute Programmatically in Magento 2:
Place all images into the **“magentoRoot\images”** directory and follow the step below.
**Step 1:** We are getting data in the root script at the below path.
**magento_root_directory\pub\Addswatchattribute.php**

Now add the code as follows.
```
<?php

use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();

$app_state = $object_Manager->get('MagentoFrameworkAppState');
$app_state->setAreaCode('frontend');

try
{
    $finalProductData = array(
        'BLKV' => array("label" => "Black", "url" => "p2.jpeg"),
        'BLKV1' => array("label" => "Black1", "url" => "p2.jpeg"),
    );

    $eavConfig = $object_Manager->get('MagentoEavModelConfig');
    $attribute = $eavConfig->getAttribute('catalog_product', 'color');

    $data = generateOptions($finalProductData, 'visual');

    $filesystem = $object_Manager->create('MagentoFrameworkFilesystem');

    $mediaDirectory = $filesystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
    $productMediaConfig = $object_Manager->create('MagentoCatalogModelProductMediaConfig');
    $tmpMediaPath = $productMediaConfig->getBaseTmpMediaPath();
    $fullTmpMediaPath = $mediaDirectory->getAbsolutePath($tmpMediaPath);

    $driverFile = $object_Manager->create('MagentoFrameworkFilesystemDriverFile');
    $driverFile->createDirectory($fullTmpMediaPath);
    $swatchHelper = $object_Manager->create('MagentoSwatchesHelperMedia');

    foreach ($data as $key => $attributeOptionsData)
    {
        if ($key == "swatchvisual")
        {
            $swatchVisualFiles = isset($attributeOptionsData['value'])
            ? $attributeOptionsData['value']
            : [];

            foreach ($swatchVisualFiles as $index => $swatchVisualFile)
            {
                if (!empty($swatchVisualFile))
                {
                    if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $swatchVisualFile))
                    {
                        $driverFile->copy(
                            __DIR__ . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $swatchVisualFile,
                            $fullTmpMediaPath . '/' . $swatchVisualFile
                        );

                        $newFile = $swatchHelper->moveImageFromTmp($swatchVisualFile);
                        if (substr($newFile, 0, 1) == '.')
                        {
                            $newFile = substr($newFile, 1);
                        }
                        $swatchHelper->generateSwatchVariations($newFile);
                        $data[$key]['value'][$index] = $newFile;
                    }
                    else
                    {
                        $data[$key]['value'][$index] = "";
                    }
                }
            }
        }
    }

    function generateOptions($values, $swatchType = 'visual')
    {
        $i = 0;
        foreach ($values as $key => $value)
        {
            $order["option_{$i}"] = $i;
            $optionsStore["option_{$i}"] = array(
                0 => $key, // admin
                1 => $value['label'],
            );
            $textSwatch["option_{$i}"] = array(
                1 => $value['label'],
            );
            $visualSwatch["option_{$i}"] = $value['url'];
            $delete["option_{$i}"] = '';
            $i++;
        }

        switch ($swatchType)
        {
            case 'text':
                return [
                    'optiontext' => [
                        'order' => $order,
                        'value' => $optionsStore,
                        'delete' => $delete,
                    ],
                    'swatchtext' => [
                        'value' => $textSwatch,
                    ],
                ];
                break;
            case 'visual':
                return [
                    'optionvisual' => [
                        'order' => $order,
                        'value' => $optionsStore,
                        'delete' => $delete,
                    ],
                    'swatchvisual' => [
                        'value' => $visualSwatch,
                    ],
                ];
                break;
            default:
                return [
                    'option' => [
                        'order' => $order,
                        'value' => $optionsStore,
                        'delete' => $delete,
                    ],
                ];
        }
    }
    $attribute->addData($data)->save();
}
catch(Exception $e)
{
    print_r($e->getMessage());
}
```

## [![Hire Magento Programmer](https://magecomp.com/blog/wp-content/uploads/2025/02/Hire-Magento-Programmer-CTA-2.webp)](https://magecomp.com/services/hire-magento-programmer/)

## Conclusion:
This way, you can create custom swatch attributes programmatically in Magento 2. Share your doubts with me through the comment box and stay in touch with us for more.
[![Magento version upgrade](https://magecomp.com/blog/wp-content/uploads/2025/02/Magento-2-Version-Upgrade-CTA-3.webp)](https://magecomp.com/services/magento-upgrade-services/)

**Happy Coding!**


---

_View the original post at: [https://magecomp.com/blog/create-custom-swatch-attribute-programmatically-magento-2/](https://magecomp.com/blog/create-custom-swatch-attribute-programmatically-magento-2/)_  
_Served as markdown by [Third Audience](https://github.com/third-audience) v3.5.3_  
_Generated: 2026-11-03 20:55:34 UTC_  
