Magento 2: How to Assign Products to Category Programmatically using Root File

Magento 2 How to Assign Products to Category Programmatically using Root File

Hello Magento Friends,

In this blog, I will show How to Assign Products to Category Programmatically using Root File in Magento 2.

hyva theme development

Assigning products to categories in Magento 2 is a critical step in organizing your online store efficiently. While the Magento admin panel provides an intuitive way to handle this, there are scenarios where assigning products programmatically becomes necessary especially when dealing with bulk updates or integrating third-party systems. In this blog, we’ll demonstrate how to assign products to a category programmatically using a root file in Magento 2.

Steps to Assign Products to Category Programmatically using Root File in Magento 2:

Step 1: First, we need to create the addProductToCategory.php file in the Magento root directory and add the code given below.

<?php

use Magento\Framework\App\Bootstrap;

try {
    require 'app/bootstrap.php';
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}

try{
  $bootstrap = Bootstrap::create(BP, $_SERVER);
  $objectManager = $bootstrap->getObjectManager();
  $state = $objectManager->get('\Magento\Framework\App\State');
  $state->setAreaCode('adminhtml');
  $productCollectionFactory = 
  $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
  $categoryLinkManagement = 
  $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
  $categoryId = Your_Category_Id;
  $productSkus = ['Product_Sku1','Product_Sku2'];
  $products = $productCollectionFactory->create()
    ->addAttributeToFilter('sku', ['in' => $productSkus]);

  foreach ($products as $product) {
    $categoryLinkManagement
      ->assignProductToCategories(
        $product->getSku(),
        array_merge([$categoryId], $product->getCategoryIds())
      );
  }

  echo "Product Assigned Successfully ";
}

catch(\Exception $e){
  print_r($e->getMessage());
}

Step 2: After the above step you will need to run the below-given URL to Assign Products to Category.

Hire Magento Programmer

https://yourdomain.com/addProductToCategory.php

Conclusion: 

The method above provides a straightforward way to Assign Products to Category Programmatically using Root File.

Need assistance with Magento 2 development? Feel free to reach out to our team of experts!

Magento version upgrade

Happy Coding!

Previous Article

How to Use Remix useBlocker and useResolvedPath on your Shopify Remix App

Next Article

Magento Statistics (2025) - Market Share, Usage and Revenue Growth

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨