You need to prepare InstallData script for category attribute as below:
<?php
/* file: app/code/{{Your_Package}}/{{module}}/Attribute/Setup/InstallData.php */
namespace {{Your_Package}}\{{module}}\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Catalog\Model\Category;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* @var EavSetupFactory
*/
private $eavSetupFactory;
/**
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
Category::ENTITY,
'custom_attribute',
[
'type' => 'varchar',
'label' => 'Custom attribute',
'input' => 'text',
'required' => false,
'sort_order' => 100,
'global' => ScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
}
}
As you may know, in the latest Magento versions, the category form for the admin panel is created via configuration file (app/code/Magento/Catalog/view/adminhtml/ui_component/category_form.xml or vendor/magento/module-catalog/view/adminhtml/ui_component/category_form.xml), so we need to create the same configuration file for our module and add our attribute to the category form. Please, see the example below:
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="custom_content">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Custom Content</item>
<item name="collapsible" xsi:type="boolean">true</item>
<item name="sortOrder" xsi:type="number">100</item>
</item>
</argument>
<field name="custom_attribute">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="sortOrder" xsi:type="number">10</item>
<item name="dataType" xsi:type="string">string</item>
<item name="formElement" xsi:type="string">input</item>
<item name="label" xsi:type="string" translate="true">Custom Attribute</item>
<item name="required" xsi:type="boolean">false</item>
</item>
</argument>
</field>
</fieldset>
</form>
Update the version of your module under etc/module.xml and run below commands to get setup upgrade:
php bin/magento setup:upgrade
You may require to remove the existing module entry from database table "setup_modules" as you want to run InstallData script.