
Making the content of your store responsive and easy to browse through guarantees improved customer experience and seamless shopping. With this thought in mind, product categories will probably be your first resort.
To assign products to categories you need to select them manually in the Products in Category section in the admin panel. However, this may get rather tedious especially if you have an extensive catalog.
Thus, you might want to optimize this process and today you'll learn how. Keep reading to learn how to add products to category programmatically in Magento 2.
Add Products to Category Using Dependency Injection
One of the most common methods of adding products to categories is dependency injection. Just use the code below.
<?php
declare(strict_types=1);
namespace Vendor\Module\Model;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
class AssignProductsToCategoryService
{
/**
* @var CategoryLinkManagementInterface
*/
protected $categoryLinkManagement;
/**
* @var ProductCollectionFactory
*/
protected $productCollectionFactory;
/**
* @param CategoryLinkManagementInterface $categoryLinkManagement
* @param ProductCollectionFactory $productCollectionFactory
*/
public function __construct(
CategoryLinkManagementInterface $categoryLinkManagement,
ProductCollectionFactory $productCollectionFactory
)
{
$this->categoryLinkManagement = $categoryLinkManagement;
$this->productCollectionFactory = $productCollectionFactory;
}
/**
* @param array $productSkus
* @param int $categoryId
* @return void
*/
public function execute(array $productSkus, int $categoryId): void
{
$products = $this->productCollectionFactory->create()
->addAttributeToFilter('sku', ['in' => $productSkus]);
foreach ($products as $product) {
$this->categoryLinkManagement
->assignProductToCategories(
$product->getSku(),
array_merge([$categoryId], $product->getCategoryIds())
);
}
}
}
Add Products to Category Using Object Manager
Alternatively, you can add products to categories using the object manager. However, make sure not to use it directly, since the object manager hides the real dependencies of the class.
<?php
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$productCollectionFactory =
$objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$categoryLinkManagement =
$objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$categoryId = 46;
$productSkus = ['24-MB01', '24-MB04'];
$products = $productCollectionFactory->create()
->addAttributeToFilter('sku', ['in' => $productSkus]);
foreach ($products as $product) {
$categoryLinkManagement
->assignProductToCategories(
$product->getSku(),
array_merge([$categoryId], $product->getCategoryIds())
);
}
Note: when applying any of the above-mentioned methods, products will be assigned to new categories and removed from the ones they were previously added to.
Adding products to categories in Magento programmatically saves your time greatly. However, you can minimize the struggle even more by creating dynamic category rules. This way, products will be added to the dynamic categories automatically based on the conditions you set.