Magento – Add a custom text field to categories in Magento 2

categorymagento2seo

I want to add a new text area to my categories in Magento2, similar to this, but its for Magento 1: adding custom drop down field to category

Basically there should be a field for each category where my customer can put in some category-based SEO content. I want to echo it later on the sidebar.

How could I achieve this? Bonus points if I can achieve this with pure XML.

Best Answer

You need to create a module that has Setup/InstallData.php with content similar to

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
        $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
        $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
        $categorySetup->removeAttribute(\Magento\Catalog\Model\Category::ENTITY, 'bottom_description');
        $categorySetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY, 'bottom_description', [
                'type' => 'text',
                'label' => 'Bottom description',
                'input' => 'textarea',
                'required' => false,
                'sort_order' => 101,
                'visible' => true,
                'wysiwyg_enabled' => 1,
                'visible_on_front' => 1,
                'is_html_allowed_on_front' => 1,
                'user_defined' => true,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'General Information',
            ]
        );
        $idg = $categorySetup->getAttributeGroupId($entityTypeId, $attributeSetId, 'General Information');
        $categorySetup->addAttributeToGroup(
            $entityTypeId,
            $attributeSetId,
            $idg,
            'bottom_description',
            46
        );

        //$installer->updateAttribute($entityTypeId, 'bottom_description', 'is_wysiwyg_enabled', 1);
        //$installer->updateAttribute($entityTypeId, 'bottom_description', 'is_html_allowed_on_front', 1);

        $installer->endSetup();
    }

Read more here.

Related Topic