Top Magento Hosting Providers for 2018
Check'em Out

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.