Add category attribute Programmatically in Magento 2.

We can create custom category attribute programmatically in Magento 2 using simple module. In our demo we have created a simple text field attribute for a category.

You can see a category attribute in the backend using Catalog -> Categories Page.
Click on Any category and you can see our custom attribute in General Section after the category name.

Create custom category attribute we need to create InstallData.php file for define our custom category attribute name.

let’s start with simple custom module to create custom category attribute,
You need to create first registration.php and module.xml file for defining our module to Magento. Here I have used Rbj as Packagename where CategoryAttrbute is the module name.

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

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

module.xml is depends on Magento_Catalog module.

Create InstallData.php file to define our custom category attribute,

Path: app/code/Rbj/CategoryAttribute/Setup/InstallData.php

Our Custom attribute code is custom_category_field and attribute title is Category Custom field and display inside General Information group.

Now we need to define our custom attribute field to category_form.xml

Path: app/code/Rbj/CategoryAttribute/view/adminhtml/ui_component/category_form.xml

We have set our custom attribute in general fieldset to display our attribute in General Group of a category page.

Now Run Setup Upgrade command to install our module in Magento.

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

Category attribute
Custom Category attribute

In front, You can get the value of Category attribute by load category object and call the function like below,

Load Category data by, Get Category data by category id

 

 

 

One Reply to “Add category attribute Programmatically in Magento 2.”

Leave a Reply

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