How To Create Magento 2 Category Programmatically – The Easiest Guide!

by admin

Magento 2 category is designed to make it easier for visitors to find products. By dividing and arranging products into suitable categories, customers can easily browse among the products and decide the best suited among them.

However, the default Magento only allows manually creating categories, which could be more efficient. If you have thousands of products in your store, it could take days to set up a category with all suitable products.

Thus, in this article, we present a step-by-step Magento 2 tutorial on how to create category and category attributes programmatically.

Let’s explore!

Tutorial To Create Category Programmatically In Magento 2

There are 2 methods to create Magento 2 category programmatically:

  • Duplicate an existing category
  • Create a dynamic category

For more details, please read the content below:

1. Duplicate category

BSS’s Duplicate Category module allows you to duplicate your category structures with a single click, saving a ton of time on category management.

After installing the extension, you will find a Duplicate button in the category edit page.

magento-2-create-category-programmatically-duplicate

Simply choose a category and click Duplicate button. Then a window will appear which allows you to edit the new duplicate category.

magento-duplicate-catalog

Here, you will need to enter the new category name, choose to duplicate assigned products and subcategories or not, and select the parent category.

Finally, click the Duplicate button to create the same category.

A successful message will appear as a new duplicate category is created.

magento-category-duplicate

*Note: You cannot duplicate the default category.

2. Create dynamic category

BSS’s Dynamic Category module allows you to import dynamic category rules from one category to another in your store. It will help you save time while creating Magento 2 category programmatically.

In the Import Category Rules dropdown, you will find a list of all dynamic categories in your store.

magento-2-create-dynamic-category-programmatically

Simply choose a dynamic category and click Import button to import its rules to the new category.

Finally, click the Save button to save configs for the category.

Moreover, our Magento 2 Dynamic Category allows you to automatically associate products to categories based on product conditions.

In order to do so, go to Catalog Categories and choose an existing category or create a new one.

On the category edit page, scroll down and expand the Products in Category section.

Here you will find the Magento Dynamic Category settings.

dynamic-catalog-magento

In Dynamic Category, choose Yes to enable automatically assign products to the category.

Then you can set up your custom rules based on default Magento product attributes ( SKU, color, attribute, etc.) for the category in Dynamic Category Rule. 

magento-dynamic-category

After finishing, please click the Save button to save configs for the category.

Fix bug: Magento 2 Products Not Showing In Category

If you’ve followed the tutorial, but on the front end, there is a message saying, “We can’t find products matching the selection,” please do as follows.

  • Check if products in the dynamic category are either Disable / Not visible individually / Out of stock / Not assign for the specific storeview.
  • If it’s not the case, reindex the dynamic category and flush your cache.
  • If it still doesn’t work, please contact our support team.

Magento 2 Create Category Attribute Programmatically

Though the default Magento 2 category attributes are good, sometimes you might need to add new ones. 

In this section, we’ll show you how to create Magento 2 category attributes programmatically.

*Note: To create category attributes programmatically in Magento, you need to use Magento 2 Hello World Module

Step 1: Create file InstallData.php

In app/code/Bss/HelloWorld/Setup, create a new file InstallData.php:

<?php

namespace Bss\HelloWorld\Setup;

use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
}

Step 2: Define the install() method

<?php
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
}

Step 3: Create Magento 2 category attribute programmatically

In app/code/Vendor/Categoryattr/Setup/InstallData.php file:

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
  
namespace Vendor\CategoryAttribute\Setup;
   
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
    
   
class InstallData implements InstallDataInterface
{
    private $eavSetupFactory; 

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }
     
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        /**
         * Add attributes to the eav/attribute
         */ 
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY,
            'custom_attribute',
            [
                'type' => 'varchar',
                'label' => 'Custom Attribute Description',
                'input' => 'textarea',
                'required' => false,
                'sort_order' => 100,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'General Information',
                'is_used_in_grid' => true,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => true,
            ]
        );
    }
}

Step 4: Display category attribute

To display category attributes in Magento 2, please follow this guide from Adobe.

Conclusion

Using BSS’s Dynamic Category module to create Magento category programmatically is a great solution to improve your workflow and category management.

We hope this article is helpful for you!

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.