How To Add Product Attributes Programmatically In Magento 2

Magento 2 is a popular e-commerce platform that offers a wide range of features and functionalities for online businesses. One of the key features of Magento 2 is its ability to handle product attribute in Magento 2. Product attributes provide additional information about a product, such as its color, size, or material.

In this article, we will discuss how to add a product attribute programmatically in Magento 2. We will provide a step-by-step guide on defining a new attribute and adding it to the product entity type using code. We will also show sample code and commands to make it easier for you to follow along.

Steps to add product attribute in Magento 2

  • Create a Module
  • Create Product Attribute
  • Run command
  • Test Product Attribute

Create a Module in Magento 2

In the previous article, we discussed in detail to create a custom module in Magento 2.

Create Product Attribute In Magento 2

Now Magento 2 introduce a new method (Data Patches) to create custom product attributes. We will use Data patches to add the custom product attribute to the database. Create a class named ProductAttributes.php in the following directory.



Code of ProductAttributes.php


namespace GDBlogger\DemoModule\Setup\Patch\Data;

use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class ProductAttriutes implements DataPatchInterface {

     * ModuleDataSetupInterface
     * @var ModuleDataSetupInterface
    private $moduleDataSetup;

     * EavSetupFactory
     * @var EavSetupFactory
    private $eavSetupFactory;

     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory          $eavSetupFactory
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;

     * {@inheritdoc}
    public function apply() {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $eavSetup->addAttribute('catalog_product', 'product_custom_attribute', [
            'type' => 'text',
            'backend' => '',
            'frontend' => '',
            'label' => 'Product Custom Atrribute',
            'input' => 'text',
            'class' => '',
            'source' => '',
            'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
            'visible' => true,
            'required' => true,
            'user_defined' => false,
            'default' => '',
            'searchable' => false,
            'filterable' => false,
            'comparable' => false,
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'unique' => false,
            'apply_to' => '',

     * {@inheritdoc}
    public static function getDependencies() {
        return [];

     * {@inheritdoc}
    public function getAliases() {
        return [];
  • The code is enclosed in a namespace “GDBlogger\DemoModule\Setup\Patch\Data”, which is a common practice in Magento 2 for creating custom modules and their components.
  • We use the “use” keyword to import the necessary classes and interfaces from the Magento\Framework and Magento\Eav namespaces.
  • The class “ProductAttributes” implements the “DataPatchInterface” interface, which provides a uniform way to apply and revert data patches in Magento 2.
  • In the constructor method, two objects are injected: “ModuleDataSetupInterface” and “EavSetupFactory”. These are dependencies that are required to perform setup and attribute-related operations.
  • When the data patch is executed, it calls the “apply” method. Inside this method, we call the “create” method of “EavSetupFactory” to create an instance of “EavSetup” with the current module setup.
  • To create a new product attribute with the specified options, such as attribute type, label, input type, visibility, etc., we use the “addAttribute” method of “EavSetup”.
  • The “getDependencies” method returns an array of data patch classes that this data patch depends on.
  • The “getAliases” method returns an array of data patch classes that can refer to this data patch.

Run Commands

After adding the Data Patch for custom product attributes. Now you need to run the following commands to add the attribute to the database.

Run setup upgrade

Php bin/magento setup:upgrdae

This command will update the database data and add the attribute to the database.

Clear cache

Now you need to clear the Magento 2 cache. After you clear the cache, Magento 2 should add your custom attribute to the customer.

Php bin/magento cache:clean

If you still haven’t created the attribute, you can run the below commands and check again.

Php bin/magento setup:di:compile
Php bin/magento setup:static-content:deploy
Php bin/magento indexer:reindex

Test Product Attribute

In your Magento 2 admin,

  • Open the Catalog > Products.
  • Open the product or click on the Add new product button
  • You can see that Magento 2 has created your custom attribute (Product Custom Attribute) here.

I hope this guide will be helpful to you. Please do not hesitate to contact us through the comments section if you have any further questions.

Leave a comment

Your email address will not be published. Required fields are marked *