🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How To Programmatically Assign Products To Multiple Categories In Magento 2

By Sanjay JethvaUpdated on May 22, 2025 2 min read

Magento 2 store is designed in such a way that shoppers find their required product easily. If that’s not the case, they may fumble into your store among the thousands of products that you offer and ultimately abandon the store due to the confusion.

We definitely do not want that to happen and hence divide the products among various categories. Category help users easily browse among the products and decide the best suited among them.

If you offer products that belong to multiple categories, maintaining it manually for each product can be tiresome. For example, you offer a t-shirt for men, you assign that product to men’s category as well as to the t-shirts category.

For a large number of products, if you have to implement such functionality, I have posted this solution to programmatically assign products to multiple categories in Magento 2.

Let’s dive right in.

Method to programmatically assign products to multiple categories in Magento 2:

<?php
use Magento\Framework\AppInterface;

try {
    require_once __DIR__ . '/app/bootstrap.php';

} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}

try {
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $objectManager->get('Magento\Framework\App\State')->setAreaCode('adminhtml');

    $newCategoryIds = array('148','152'); // It should be category Ids
    $sku = 'tshirt'; // It should be Product SKU

    $categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
    $categoryLinkRepository->assignProductToCategories($sku, $newCategoryIds);

} catch (\Exception $e) {
    echo "<pre>";
    print_r($e->getMessage());
    echo "</pre>";
}

It is a Magento 2 Root Script.

That’s it. You canset product position in a category in Magento 2 as the product position value determines the order of products on the category page.

You can also programmatically set URL key of the category in Magento 2, in case you are importing products to your store in bulk and want to create SEO-friendly category pages.

Do share the solution with the Magento community via social media.

Thank you.

Sanjay Jethva Full Image
Article bySanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.