Magento 2 provides inbuilt functionality to assign and remove products from the category under Magento 2 admin > Products > Categories section. However, there are situations when we need to dynamically assign and remove products from a category. In this article we will show you how to link products to categories in Magento 2 programmatically.
1. Adding products to category:
To ensure that you have all the data needed for the code, you will have to get the category ID that you want to add to the product and the product ID of that product.
For example, we will add any product to the “Wine” category after saving the product.
Note: You can get category ID from Catalog > Categories
* Step 1: Add an observer for the saving product event.
<event name="catalog_product_save_after">
<observer name="save_category_data" instance="Magenest\Movie\Observer\AfterProductSave"/>
</event>
* Step 2: Create AfterProductSave observer with addition argument – inject the CategoryLinkManagementInterface:
protected $categoryLinkManagementInterface;
public function __construct(
....
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkManagementInterface
)
{
...
$this->categoryLinkManagementInterface = $categoryLinkManagementInterface;
}
* Step 3: Add the product to the new category.
Note: $categoryId = [42] is the array of category ID that we use for this example
public function execute(Observer $observer)
{
$data = $this->request->getParams();
$id = $data['id'];
$product = $this->productFactory->create()->load($id);
$categoryId = [42];
$categoryIds = array_unique(
array_merge(
$product->getCategoryIds(),
$categoryId
public function execute(Observer $observer)
{
$data = $this->request->getParams();
$id = $data['id'];
$product = $this->productFactory->create()->load($id);
$categoryId = [42];
$categoryIds = array_unique(
array_merge(
$product->getCategoryIds(),
$categoryId
)
);
$this->categoryLinkManagementInterface->assignProductToCategories(
$product->getSku(),
$categoryIds
);
}
assignProductToCategories() will replace the existing categories list – therefore we have to add our category to the existing list, before assigning this list to the product.
See more here: https://magenest.com/en/how-to-link-products-to-categories-in-magento-2-programmatically/
Comments
Post a Comment