Magento 2: Assign/Remove Products from Categories

This article shows how you can programmatically assign a product to multiple categories and how you can remove a product from a category in Magento 2.

I am using a standalone script for this purpose using Object Manager. You can use this code in your custom module as well by using Dependency Injection (DI) instead of Object Manager.

Initialize Object Manager and Set the Area code

The following things are done in the below code:

– Initialize the object manager.
– Set the area code as adminhtml as we are editing the product.
– Define the logger to log information about the delete process. Zend Logger is used.


<?php
error_reporting(1);
set_time_limit(0);
ini_set('memory_limit', '2048M');

use Magento\Framework\App\Bootstrap;
 
/**
 * If your external file is in root folder
 */
require __DIR__ . '/app/bootstrap.php';
 
/**
 * If your external file is NOT in root folder
 * Let's suppose, your file is inside a folder named 'xyz'
 *
 * And, let's suppose, your root directory path is
 * /var/www/html/magento2
 */
// $rootDirectoryPath = '/var/www/html/magento2';
// require $rootDirectoryPath . '/app/bootstrap.php';
 
$params = $_SERVER; 
$bootstrap = Bootstrap::create(BP, $params); 
$objectManager = $bootstrap->getObjectManager();

// Set Area Code
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); // or \Magento\Framework\App\Area::AREA_FRONTEND, depending on your need

// Define Zend Logger
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/assign-remove-product-to-category.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

You need to have the product SKU for this purpose.

If you don’t have the product SKU and only have the product ID, then you can load the product with the product ID and then get its SKU.

Get Product SKU from Product ID


$productId = 897; // product ID
$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
$product = $productRepository->getById($productId);
$sku = $product->getSku(); // product SKU

Assign a Product to Multiple Categories


/**
 * Assign product to categories
 */ 
$categoryIds = ['10', '18', '38'];
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface'); 
$categoryLinkRepository->assignProductToCategories($sku, $categoryIds);

Remove a Product from a Category


/**
 * Remove product from category
 */ 
$categoryId = 10;
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Model\CategoryLinkRepository');
$categoryLinkRepository->deleteByIds($categoryId, $sku);

Hope this helps. Thanks.