Magento 2.x – How to add a new product custom attribute programmatically


One of the most popular operations that we will need on Magento, is adding a custom attribute to our catalog products. To do so, basically, we will need to perform the following steps:

  1. Create a new module
  2. Create an InstallData script
    • app/code/Offset101/ProductAttributeExample/Setup/InstallData.php:
    • We can optionally add the following:
      • ‘source’ : A Source model to provide a list of options. We will need to write the method “getAllOptions”.
      • ‘backend’: A backend model to allow you to perform certain actions when an attribute is loaded or saved. ie: a validation. We will need to write the method validate(Object).
      • ‘frontend’: A frontend model to define how it should be rendered on the frontend. We will need to write method getValue(Object).
  3. Execute the InstallData script and verify that it works

    • After running this, the new attribute should have been added to the database. You can check the eav_attribute and catalog_eav_attribute tables to verify that the attribute and its properties are there.
    • If the attribute is there, but you need to change something, or re-run your script, you can easily remove the row of your script (or downgrade the version) on the setup_module table.

For more information, you can follow up the following link: How to Add a New Product Attribute