Magento 2 Add Category Attribute

You can add a new category attribute with the help of InstallData.php.

Create InstallData.php

File : app/code/PHPCodez/First/Setup/InstallData.php

 namespace Vendor\Module\Setup;
 use Magento\Framework\Setup\InstallDataInterface;
 use Magento\Framework\Setup\ModuleContextInterface;
 use Magento\Framework\Setup\ModuleDataSetupInterface;
 class InstallData implements InstallDataInterface {
 protected $_pageFactory;
 public function __construct(\Magento\Cms\Model\PageFactory $pageFactory) {
 $this->_pageFactory = $pageFactory;
 public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

 'type' => 'varchar',
 'label' => 'PHPCodez Category',
 'input' => 'text',
 'sort_order' => 100,
 'source' => '',
 'global' => 1,
 'visible' => true,
 'required' => false,
 'user_defined' => false,
 'default' => null,
 'group' => '',
 'backend' => ''

Display the category attribute

The category UI Component is rendered with configuration from the category_form.xml file. All files with that name are merged together. As a result, We will add a field by creating a category_form.xml file in the app/code/Mageplaza/HelloWorld/view/adminhtml/ui_component/ directory.

<?xml version="1.0" ?>
<form xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
 <fieldset name="general">
 <field name="phpcodez_category">
 <argument name="data" xsi:type="array">
 <item name="config" xsi:type="array">
 <item name="required" xsi:type="boolean">false</item>
 <item name="validation" xsi:type="array">
 <item name="required-entry" xsi:type="boolean">false</item>
 <item name="sortOrder" xsi:type="number">333</item>
 <item name="dataType" xsi:type="string">string</item>
 <item name="formElement" xsi:type="string">input</item>
 <item name="label" translate="true" xsi:type="string">PHPCodez Category</item>

Issue the following comnands and go to admin section and the new attribute will be vailable in category add/edit section.

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean

Leave a Reply

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