Magento 2 categories help make your store organized and easy to browse through. They enhance navigation greatly since customers can jump from one category to another without looking for some item in the entire catalogue.
As you know, you can easily create and manage Magento 2 categories in the admin panel. That's the most common way. But there is also a different approach.
You can also create a category in Magento 2 programmatically. In this guide, you'll find two methods to do so.
Post Contents [hide]
Create Magento 2 Category Using Dependency Injection
One of the methods to create a category programmatically is to use dependency injection. Here is the code you have to run:
<?php
declare(strict_types=1);
namespace Vendor\Module;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Catalog\Model\CategoryRepository;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\CouldNotSaveException;
use Psr\Log\LoggerInterface;
class CreateCategoryService
{
protected $storeManager;
protected $categoryCollectionFactory;
protected $categoryRepository;
protected $logger;
public function __construct(
StoreManagerInterface $storeManager,
CollectionFactory $categoryCollectionFactory,
CategoryRepository $categoryRepository,
LoggerInterface $logger
)
{
$this->storeManager = $storeManager;
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->categoryRepository = $categoryRepository;
$this->logger = $logger;
}
public function execute(string $categoryName)
{
$category = $this->categoryCollectionFactory->create()
->addAttributeToFilter('name', $categoryName)
->getFirstItem();
if ($category->getId()) {
return $category;
}
$parentId = $this->storeManager->getStore()->getRootCategoryId();
try {
$parentCategory = $this->categoryRepository->get($parentId);
} catch (NoSuchEntityException $noSuchEntityException) {
$this->logger->error('This is an error while getting rootCategory');
return $category;
}
$category->setPath($parentCategory->getPath())
->setParentId($parentId)
->setName($categoryName)
->setIsActive(true);
try {
$this->categoryRepository->save($category);
} catch (CouldNotSaveException $couldNotSaveException) {
$this->logger->error('This is an error while saving category');
return $category;
}
return $category;
}
}
Create Magento 2 Category Using Object Manager
Alternatively, you can create a Magento 2 category using the object manager. Yet, keep in mind that the direct usage of this method hides the real dependencies of the class.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get(Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');
$categoryFactory = $obj->create(\Magento\Catalog\Model\CategoryFactory::class);
$storeManager = $obj->create(\Magento\Store\Model\StoreManagerInterface::class);
$categoryName = 'test category';
$parentId = $storeManager->getStore()->getRootCategoryId();
$parentCategory = $categoryFactory->create()->load($parentId);
$categoryFactory->create()->setPath($parentCategory->getPath())
->setParentId($parentId)
->setName($categoryName)
->setIsActive(true)
->save();
So, this is how you create Magento categories programmatically. You can go with whatever option you find more suitable. Once categories are created, you may also need to add products to categories programmatically.
To make you category management even more efficient, you can create dynamic category rules and let your products be added to and removed from the categories automatically. Isn't this a time-saver?