Being adobe commerce developers, we get different tasks every day in which we need to resolve issues or we need to develop functionality according to requirements.
Magento 2 provides the best facilities to create / updates or import products from Admin area. However, we need to create a module in order to customize or fulfill some complex requirements. For example, Allow admin to add products to categories from different areas of the admin than default like configuration of custom admin form, or create products programmatically using custom console command etc.
In this Blog, we will see how we can assign or add products in different categories using code. Let’s say, we are going to assign products to categories programmatically.
Let’s assume that we have created the basic files of the module. I am creating a service class which is responsible for assigning products in different categories.
Add products in categories in Magento 2
Create a service class inside the appropriate VendorName/ModuleName/Service class. In my case, VendorName is SbDevBlog and ModuleName is Catalog
Create AddProductsToCategoriesService.php inside SbDevBlog/Catalog/Services
<?php
/**
* @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
*/
namespace SbDevBlog\Catalog\Services;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Framework\Exception\CouldNotSaveException;
use Psr\Log\LoggerInterface;
class AddProductsToCategoriesService
{
/**
* @var CategoryLinkManagementInterface
*/
private CategoryLinkManagementInterface $categoryLinkManagement;
/**
* @var LoggerInterface
*/
private LoggerInterface $logger;
/**
* Constructor For Service
*
* @param CategoryLinkManagementInterface $categoryLinkManagement
* @param LoggerInterface $logger
*/
public function __construct(
CategoryLinkManagementInterface $categoryLinkManagement,
LoggerInterface $logger
){
$this->categoryLinkManagement = $categoryLinkManagement;
$this->logger = $logger;
}
/**
* Add Products To Categories
*
* @param string $sku
* @param array $categoryIds
*
* @return bool
*/
public function addProductToCategories(string $sku, array $categoryIds):bool
{
try {
$this->categoryLinkManagement->assignProductToCategories(
$sku,
$categoryIds
);
return true;
} catch (CouldNotSaveException $e) {
$this->logger->error($e->getMessage());
}
}
return false;
}
}
I have shown you how we can assign a product to new categories, but please make sure to check whether your product is assigned to any category or not. If categories are assigned than get assigned category ids and merge with your new category ids, otherwise you may lose your existing links of categories. You can achieve this with the below method.
$categoryIds = array_merge($product->getCategoryIds(), $newCategoryIds);
$this->categoryLinkManagement->assignProductToCategories(
$product->getSku(),
$categoryIds
);
Thank you for visiting sbdevblog.
Do you want to add multiple products to cart programmatically ? Than visit https://sbdevblog.com/magento-2-add-multiple-products-to-cart-programmatically/
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂