Use code MGT25 to get $25 off! Limited time offer on Cloudways Magento hosting

How to Create Attribute and Attribute Set Programmatically in Magento 2

An attribute is the property of a product and can be highly useful in an ecommerce store. It can be used for multiple purposes like creating different types of products and changing their descriptions, etc., for better search functionality for your customers.

You can easily create attribute and attribute set in Magento 2 from the admin panel. However, many people still inquire about how to create an attribute and attribute set programmatically. Hence, I’ll show you how to create one.

First, I’ll have to create a custom module.

Configure and Register Custom Module

First, let’s configure the module. Create module.xml file in app/code/Magenticians/Mymodule/etc and add this code in it:

Now to register the module create registration.php in app/code/Magenticians/Mymodule and add this code in it:

Create Attribute and Attribute Set

Create InstallData.php in app/code/Magenticians/Mymodule/Setup and add this code in it:

In the code above, I have created an attribute set, and then created an attribute that I assigned to the attribute set.

Run CLI Commands

Connect your store with an SSH terminal and then run these commands in the root directory of your store:

Now just check the result by going to STORES → Attribute Set, here you will see the new attribute set MyCustomAttribute:

attribute set result

And then click on MyCustomAttribute, here you will see attribute text_my_custom_attribute:

attribute result

Final Words

I believe that after following this tutorial you should be able to create custom attribute and attribute set in Magento 2. If you still face any issue related to this guide, just use the comment box below!

About Author

Syed Muneeb Ul Hasan is an expert in PHP and Magento, he prefers to educate users in implementing and learning Magento. When not working, he loves to watch cricket.

  • Vishwanath Kharabe

    I followed your code to create custom attribute set and custom attribute. But my custom attribute gets assigned to all the attribute sets. I want to assign it to specific attribute set only. Please guide.

  • Artur Rain

    Can you share the code, to add the attribute to the existing Attribute sets, without creating the new Attribute set? Also, where is the option to mark System: NO ? Because now the attribute created with this code is market as system and I don’t need it to be marked as system. Thank you