How to create Product attribute programmatically in Magento 2?

Up to Magento 2.2 Version, We can create product attributes programmatically using the InstallData.php file.

Using dynamically create product attribute save the time for creating attribute manually using the admin panel.

If you are creating an extension package and you need product attribute at that time below code snippet will be helpful for creating Product attribute.

We can create product attribute manually using Stores -> Attributes -> Product -> Add New Attribute.

To create product attribute, We need to create a simple module for that,

You need to create the first registration.php and module.xml file for defining our module. Here I have used Rbj as Packagename where ProductAttribute is a module name.

Path: app/code/Rbj/ProductAttribute/registration.php

Create module.xml file, Path: app/code/Rbj/ProductAttribute/etc/module.xml

Create InstallData.php file for install our custom product attribute in Magento instance.

We are creating two custom product attribute, first select option, custom attribute and other one is the text field.
Path: app/code/Rbj/ProductAttribute/Setup/InstallData.php

We have used Custom Product Attribute as a new Group on the product page. In the Custom Product Attribute tab section our new product attribute will display.

For Select option, we need to take type as int and for a text field, we need to take a type as varchar. All other fields are self-explanatory in the above code snippet.

For select option, We need to create Model file for define our custom option of select box,
$statusOptions = ‘Rbj\ProductAttribute\Model\Config\Source\StatusOptions’;
We have create StatusOptions.php file under Model and define our enable and disable option value.

Create StatusOptions.php file,
Path: app/code/Rbj/ProductAttribute/Model/Config/Source/StatusOptions.php

Using Command-line, Go to Magento instance where you have installed Magento, Open Command Line,

custom product attibute in Magento 2
custom product attribute in Magento 2

For Create Category Attribute, Category Attribute programmatically in Magento 2