How To Programmatically Assign Products To Multiple Categories In Magento 2

Written by Jigar Patel

Dec 18, 2021

How To Programmatically Assign Products To Multiple Categories In Magento 2

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

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 "<pre>";
    print_r($e->getMessage());
    echo "</pre>";
}

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.

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP