magento 2 assign product to category programmatically

How to Assign Product to Category Programmatically in Magento 2?

by admin

In this post, we will show you a comprehensive guide on Magento 2 assign product to category programmatically.

Magento 2 store design makes it easy for customers to find specific products. Without that ease, customers will struggle to navigate through a large number of products and may abandon the store due to confusion.

To handle this case, BSS Commerce highly recommends categorizing products into groups. These groups allow customers to browse through the products more easily and select the right one.

But for products that belong to multiple categories, manually managing this for each product can be a pain. So in this post, we will show you a comprehensive guide on how to assign products to categories programmatically in Magento 2 via 3 methods including:

  • Method 1: Using Object Manager
  • Method 2: Using the Dependency Injection
  • Method 3: Using Dynamic Category Extension

Now, let us proceed with the details!

Brief Overview of Product Categorization in Magento 2

Product categorization is a core part of Magento 2 and affects your store’s user experience and search functionality. It’s about grouping products into a hierarchy so products are more findable and navigable.

Key parts of product categorization in Magento 2

  • Categories: These are containers that hold related products. They are hierarchical with parent and child categories.
  • Product assignments: Each product can be assigned to one or multiple categories. This determines where the product shows up in the store navigation and search results.
  • Category attributes: Categories can have custom attributes to add extra information or filtering options for products in that category.
  • Category paths: The hierarchy of categories creates unique paths for each category used for URL and navigation.
  • Category pages: Each category can have a dedicated page with custom content, layout and product display options.

product categorization

Thanks to effectively assigning products to categories programmatically in Magento 2, you can boost customer satisfaction, SEO, and sales conversions. In the following section, explore the three methods to assign product to category programmatically in Magento 2 compiled by the BSS Commerce blog.

Magento 2 Assign Product to Category Programmatically: Step-by-Step

Here are complete guides to assign products to categories programmatically in Magento 2 via three methods:

  • Method 1: Using Object Manager
  • Method 2: Using the Dependency Injection
  • Method 3: Using Dynamic Category Extension

Let us begin by exploring each method in detail:

Method 1: Using Object Manager

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$categoryIds = array('101','102');
$sku = '24-MB01';
$categoryLinkRepository->assignProductToCategories($sku, $categoryIds);

This code snippet includes two parameters: the SKU of the product and an array of categories for the assignProductToCategories function. It is important to note that executing this code will result in the removal of the product from its previously assigned categories and the assignment of the product to the newly specified categories.

For example, if SKU ‘24-MB01’ is currently associated with category IDs 99 and 100, after executing the aforementioned code, SKU ‘24-MB01’ will be removed from category IDs 99 and 100 and will instead be assigned to category IDs 101 and 102.

Bonus Tips: Methods for Programmatically Removing Products from a Category Utilizing Object Manager

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Model\CategoryLinkRepository');
$categoryId = 101;
$sku = '24-MB01';
$categoryLinkRepository->deleteByIds($categoryId,$sku);

This code snippet includes two parameters: category ID and SKU, which are passed to the deleteByIds function. It is important to note that executing this code will result in the removal of products solely from the specified category, rather than from all categories to which they were previously assigned.

For example, if SKU ‘24-MB01’ is associated with categories 99, 100, and 101, the execution of the aforementioned code will only eliminate SKU ‘24-MB01’ from category 101.

Method 2: Using The Dependency Injection

The following code snippet can be used to programmatically assign products to a specific category:

<?php

public function assignProductsToCategory(){
	$this->getCategoryLinkManagement()
	->assignProductToCategories(
		$product->getSku(),
		$product->getCategoryIds() 
	);
}
private function getCategoryLinkManagement() { 

	if (null === $this->categoryLinkManagement) { 
		$this->categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
		->get('Magento\Catalog\Api\CategoryLinkManagementInterface'); 
		} 

	return $this->categoryLinkManagement; 
}

>>> If you need a guide for configuring Magento features, let’s dive in this blog: Magento 2 tutorial for beginners step by step

Method 3: Using Magento 2 Dynamic Category Extension: The Fastest & Easiest Way

Currently, coding is available in the Magento community but those codes have limitations, no updates, or face compatibility issues that may conflict with existing codes in your store. As a result, the recommended approach for programmatically assigning products to categories in Magento 2 is through the use of plugins. Implementing the Magento 2 Dynamic Category Extension is a highly effective strategy to guarantee compatibility, reduce potential issues, and receive exceptional support from experienced developers.

The Magento 2 Dynamic Category extension created by BSS Commerce offers an excellent solution that allows for the automatic association of products to categories based on specified product conditions.

  • Review: 99% positive
  • Compatible with Hyva Theme
  • Compatible with Magento 2.4.7 and PHP 8.2
  • Pricing: $79/one-time payment
  • Free one-year support
  • Free installation
  • Free lifetime update
  • 30 days money back guarantee

Magento 2 Dynamic Category extension

Highlight Features of Magento 2 Dynamic Category Extension

BSS Magento 2 automatic categories extension offers the following features:

  • Bulk assign products to categories automatically: This Magento 2 Dynamic Category module auto-categorizes products based on your rules. Also, it monitors product attribute changes to update categories as needed.
  • Create multiple criteria to categorize products: This extension auto-assigns products to specific categories using product attributes and conditions. You can create conditions of any complexity level.
  • Preview products before saving: Once the rules are set, the Magento 2 Automatic Categories extension will show you the products that will be added to the category based on your conditions.
  • Reindex matching products for category: Magento 2 module to assign products to categories programmatically reindexes matching products in category. When changes occur you can reindex the relevant products by clicking the Reindex matching products button below the rules section and then save the category.

Assign Product to Category in Magento 2 Using Dynamic Category Extension

In this section, we will show you a comprehensive step-by-step guide on how to use Magento 2 Dynamic Category to assign product to category programmatically.

Step 1: Enable Magento 2 Dynamic Category

After installing our module, please go to Stores ⇒ Configuration ⇒ Catalog ⇒ BSS COMMERCE ⇒ Dynamic Category to enable it.

Step 2: Setup the rule for the dynamic category

Next, go to Catalog ⇒ Categories. Choose an existing category or create a new one, then expand the Products in Category section.

Here you will find the Dynamic Category configuration.

In Dynamic Category, choose Yes to allow the module to assign the products for the category based on the conditions you set up below.

In case you want to import the rule from another dynamic category that you had set up in your store, you can select that category in Import Category Rules.

Or else, you can create a new set of product conditions for the category in Dynamic Category Rule.

Our module uses default Magento product attributes (including SKU, color, attribute, etc.) to set conditions for creating dynamic categories.

After setting up the dynamic category rule, click the Refresh matching products button to preview all products that meet the rule you set up in a product grid.

Then you click Save to save the dynamic category settings.

And that’s done!

The Bottom Line

Magento 2 assign product to category programmatically is an efficient method for online store owners. By using these methods, you can automate product organization, save time, and reduce human error. Now you know the basics of products, categories, and their relation to managing your product catalog and customer experience better. Optimize for performance, error handling, and testing thoroughly.

BSS Commerce Blog is a go-to resource for Magento merchants, developers, and consultants. We also provide full Magento eCommerce development services for our clients. Whether you need consulting for your Magento store, website deployment, site customization and maintenance, or module and third-party service integration, our experienced Magento 2 Development Team will fulfill all your needs. Contact us to get more.

FAQs – How to Assign Product to Category in Magento 2 Programmatically

1. How do I remove a product from a category programmatically?

You can use the CategoryLinkManagementInterface to remove a product from a category by deleting the corresponding CategoryLink entity.

2. Can I change the position of a product within a category programmatically?

Yes, you can update the position attribute of the CategoryLink entity to change the product’s position.

3. What are the necessary dependencies for assigning products to categories?

You’ll typically need dependencies for the ProductRepository, CategoryRepository, and CategoryLinkManagementInterface.

4. How do I handle errors or exceptions when assigning products to categories?

Implement proper error handling mechanisms using try-catch blocks to gracefully handle exceptions and provide informative error messages.

5. Can I use cron jobs to automate product category assignments?

Yes, you can schedule cron jobs to periodically update product categories based on specific criteria.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.