Magento 2 – How to Add Product Attribute Programmatically

In this post I am going to explain how to add product attribute programmatically in magento 2.

We are going to create three custom product attributes. Yes/No, Select Option and Text field.

We need to create the data setup script(InstallData.php) with parameters of the new attribute.

File path: app/code/Ht/Mymodule/Setup/InstallData.php


We have created the three custom product attributes.

Custom Text Field -> Text Box
Custom Yes/No -> Yes/No Field
Custom Dropdown -> Select Box

“Custom Dropdown” is a select box and we have defined a custom source: Ht\Mymodule\Model\Source\Customdropdown

So, we need to create the source file as well.

File path: app/code/Ht/Mymodule/Model/Source/Customdropdown.php


At Final, Open terminal/SSH and navigate to Magento 2 setup root directory and run below commands.


Magento 2 - How to Add Product Attribute Programmatically


  1. Very well explained, Thanks for sharing such an amazing article.

  2. Thank for sharing!

Leave a Reply

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