country collection

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

The below 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.
ini_set('memory_limit', '2056M');
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();

Here we need product SKU for this operation, if you have product ID then follow below instruction to get product 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 will helps you!