---
title: "How To Programmatically Assign Products To Multiple Categories In Magento 2"
url: "https://dolphinwebsolution.com/how-to-programmatically-assign-products-to-multiple-categories-in-magento-2"
date: "2021-12-18T04:57:37+05:30"
modified: "2023-08-24T09:21:11+05:30"
author:
  name: "Jigar Patel"
categories:
  - "Magento"
word_count: 421
reading_time: "3 min read"
summary: "Magento 2 allows store admins to add and remove products from the category under Magento 2 Admin panel &gt; CATALOG &gt; Categories &gt; Products in Categories the section. But sometimes we need to..."
description: "Magento 2 allows store admins to add and remove products from the category under Magento 2 Admin panel &gt; CATALOG &gt; Categories &gt; Products in Categori..."
keywords: "Programmatically Assign Products,assignProductToCategories,add and remove products,remove products from facebook shop,Multiple Categories, Magento"
language: "en"
schema_type: "Article"
related_posts:
  - title: "How To Develop Auto Parts Ecommerce Website?"
    url: "https://dolphinwebsolution.com/blog/how-to-develop-auto-parts-ecommerce-website/"
  - title: "How to Download Csv File in Magento 2"
    url: "https://dolphinwebsolution.com/how-to-download-csv-file-in-magento-2"
  - title: "Migration to Magento 2:  Why is it so essential?"
    url: "https://dolphinwebsolution.com/migrate-to-magento-2-why-is-it-so-essential"
---

# How To Programmatically Assign Products To Multiple Categories In Magento 2

_Published: December 18, 2021_  
_Author: Jigar Patel_  

![](https://dolphinwebsolution.com/wp-content/uploads/2023/02/How-To-Programmatically-Assign-Products-To-Multiple-Categories-In-Magento-2-1024x536.png)

Magento 2 allows store admins to add and remove products from the category under **`Magento 2 Admin panel > CATALOG > Categories > Products in Categories`** the section. But sometimes we need to assign the products among various categories. Category help visitor easily finds the product and decide the best suited among them.

If black Friday offers products that belong to other categories maintaining it manually for a one-by-one product can be time-consuming. For Example some of the products black Friday offers, you can assign that product to the Black Friday category.

**Read This:** [How To Get Product Salable Quantity In Magento 2](https://dolphinwebsolution.com/magento-2-get-product-salable-quantity-programmatically)

Using interface, **Magento\\Catalog\\Api\\CategoryLinkManagementInterface** with **assignProductToCategories**($productSku, array $categoryIds) method used to add to specific category programmatically.

For a large number of products, if you have to implement such functionality.

## Step To Programmatically assign products to multiple categories in Magento 2:

```
<?php

use Magento\Framework\App\Bootstrap;

try {
    require_once __DIR__ . '/app/bootstrap.php';
} catch (\Exception $e) {
    echo 'error: ' . $e->getMessage();
    exit;
}
try {
    $params = $_SERVER;
    $bootstrap = Bootstrap::create(BP, $params);
    $obj = $bootstrap->getObjectManager();

    $state = $obj->get('Magento\Framework\App\State');
    $state->setAreaCode('frontend');
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $prodColl = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
    $categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
    $ids = array('1', '2');// here assign your product ids.
    $porIds = implode(',', $ids);
    $collection = $prodColl->addAttributeToSelect('*');
    $collection->addFieldToFilter('sku', array('in' => $porIds));;
    $data = array();
    foreach ($collection as $pCollection) {
        $categoryId = ['108','104']; // here add your category id.
        if (in_array('108', $pCollection->getCategoryIds())) {
            continue;
        }
        $categoryIds = array_unique(array_merge($pCollection->getCategoryIds(), $categoryId));
        $sku = $pCollection->getSku();
        $product = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($pCollection->getId()); //get parent product id from product id.
        if (isset($product[0])) {
            //echo 'parent-->' . $product[0].PHP_EOL;
            $productConf = $objectManager->create('Magento\Catalog\Model\Product')->load($product[0]); // Load configurable product
            $sku = $productConf->getSku();
        }
        if (!in_array($sku, $data)) {
            //echo 'parent-->' . $sku . PHP_EOL;
            $categoryLinkRepository->assignProductToCategories($sku, $categoryIds);
        }
        $data[] = $sku;
    }
} catch (\Exception $e) {
    echo "";
    print_r($e->getMessage());
    echo "";
}
```

**assignProductToCategories($productSku, array $categoryIds)** Add Product SKU as $sku value and Pass Category id as array value in $categoryId variable. If you want to assign products to a single category, add only a single category id value otherwise add multiple category id values.

It is a Magento 2 Root Script.


---

_View the original post at: [https://dolphinwebsolution.com/how-to-programmatically-assign-products-to-multiple-categories-in-magento-2](https://dolphinwebsolution.com/how-to-programmatically-assign-products-to-multiple-categories-in-magento-2)_  
_Served as markdown by [Third Audience](https://github.com/third-audience) v3.5.3_  
_Generated: 2026-08-26 06:14:35 UTC_  
