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

 

 

 

2 Replies to “Add category attribute Programmatically in Magento 2.”

  1. Hi. Everything wors ok with the custom attribute for the category, except retrieving the value put in the custom input for every category.

    I’ve put this code :
    $getCategory = CATEGORY_OBJECT;
    echo $getCategory->getCustomCategoryField();
    In the Magento_Theme/templates/html/title.phtml file, to replace the default h1 title for categies pages, with a longer version of title, but I have some errors:
    Use of undefined constant CATEGORY_OBJECT – assumed ‘CATEGORY_OBJECT’

    I did not execute this step “Load Category data by, Get Category data by category id” from the link
    https://www.rakeshjesadiya.com/how-to-get-category-collection-by-category-id-in-magento-2/

    because I didn’t understand exactly where to put that info. On what file.
    Can you please help me? Thanks

Leave a Reply

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