Magento 2 Add Category Attributes Programmatically

Magento 2 Category Attributes Programmatically is a timely topic so that you can work on custom magento 2 extension, for example, in the right way. Welcome here, Mageplaza Tutorial! The exact steps are listed with the specific script in PHP to create the category attributes. By the availability of the setup scripts, there is no need to waste time learning or modifying anything while you don’t have experience in coding. The only thing you need to do is copying and pasting the following snippets to your module. Here are the snippets that you can achieve immediately.

Step 1: Create UI Component

view/adminhtml/ui_component/category_form.xml

<?xml version="1.0" ?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
	<fieldset name="general">
		<field name="mp_new_attribute">
			<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>
					<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">Mageplaza new attribute</item>
				</item>
			</argument>
		</field>
	</fieldset>
</form>

Step 2: Create setup file InstallData.php

Mageplaza/HelloWorld/Setup/InstallData.php - Snippet #1

<?php 


namespace Mageplaza\HelloWorld\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; 
 
class InstallData implements InstallDataInterface {

	/**
	 * @var \Magento\Eav\Setup\EavSetupFactory
	 */
	private $eavSetupFactory;

	/**
	 * Constructor
	 * 
	 * @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
	 */
	public function __construct(EavSetupFactory $eavSetupFactory)
	{
		$this->eavSetupFactory = $eavSetupFactory;
	}

	/**
	 * {@inheritdoc}
	 */
	public function install(
		ModuleDataSetupInterface $setup,
		ModuleContextInterface $context
	)
	{
		$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

		$eavSetup->addAttribute(
		    \Magento\Catalog\Model\Category::ENTITY,
		    'mp_new_attribute',
		    [
		        'type' => 'varchar',
		        'label' => 'Mageplaza Attribute',
		        'input' => 'text',
		        'sort_order' => 100,
		        'source' => '',
		        'global' => 1,
		        'visible' => true,
		        'required' => false,
		        'user_defined' => false,
		        'default' => null,
		        'group' => 'General Information',
		        'backend' => ''
		    ]
		);
	}
}

Mageplaza/HelloWorld/Setup/InstallData.php - Snippet #2

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Mageplaza\HelloWorld\Setup;
use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Setup\CategorySetupFactory;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * Category setup factory
     *
     * @var CategorySetupFactory
     */
    private $categorySetupFactory;

    /**
     * Init
     *
     * @param CategorySetupFactory $categorySetupFactory
     */
    public function __construct(CategorySetupFactory $categorySetupFactory)
    {
        $this->categorySetupFactory = $categorySetupFactory;
    }
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    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, 'my_attribute',
    );
        $categorySetup->addAttribute(
        \Magento\Catalog\Model\Category::ENTITY, 'my_attribute', [
             'type' => 'int',
             'label' => 'My Atrribute ',
             'input' => 'select',
             'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
             'required' => false,
             'sort_order' => 100,
             'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
             'group' => 'General Information',
        ]
    );
    $idg =  $categorySetup->getAttributeGroupId($entityTypeId, $attributeSetId, 'General Information');
    $categorySetup->addAttributeToGroup(
        $entityTypeId,
        $attributeSetId,
        $idg,
        'my_attribute',
        46
    );
$installer->endSetup();
    }
}

Step 3: Flush cache & Upgrade

In this step we need to flush Magento cache and run upgrade command line

  1. Flush Cache Run flush cache here

  2. Run upgrade command line:

Then run command php bin/magento setup:upgrade



Next tutorial:

Module Development Series



Enjoyed the tutorial? Spread it to your friends!

magento-2-tutorial
category
attributes
programmatically
featured

Comments for Magento 2 Add Category Attributes Programmatically

Please leave comments if you have any questions, feedbacks.

Module Development

You also may like these Magento 2 Extensions

One Step Checkout

$199
10 reviews

Layered Navigation

$99
12 reviews

SEO

FREE
no review

Shop By Brand

$99
3 reviews

People also searched for:

  • Magento 2 category attributes programmatically
  • Create category attributes in Magento 2
  • Magento 2 create category attributes
  • Creating category attributes programmatically
  • Searches related to Magento 2 Category Attributes
  • magento 2 create category attribute programmatically
  • magento 2.1 create category attribute
  • magento 2 create category programmatically
  • magento 2 add category attribute programmatically
  • magento 2.1 add category attribute
  • how to add new custom category attribute in magento
  • magento add category attribute programmatically
  • magento 2 custom category attribute