Skip to main content

HOW TO LINK PRODUCTS TO CATEGORIES IN MAGENTO 2 PROGRAMMATICALLY

 Magento 2 provides inbuilt functionality to assign and remove products from the category under Magento 2 admin > Products > Categories section. However, there are situations when we need to dynamically assign and remove products from a category. In this article we will show you how to link products to categories in Magento 2 programmatically.

1. Adding products to category:

To ensure that you have all the data needed for the code, you will have to get the category ID that you want to add to the product and the product ID of that product.

For example, we will add any product to the “Wine” category after saving the product.

Note: You can get category ID from  Catalog > Categories

Step 1: Add an observer for the saving product event.

<event name="catalog_product_save_after">
       <observer name="save_category_data" instance="Magenest\Movie\Observer\AfterProductSave"/>
</event>

Step 2: Create AfterProductSave observer with addition argument – inject the CategoryLinkManagementInterface:

protected $categoryLinkManagementInterface;
 
   public function __construct(
       ....
      \Magento\Catalog\Model\ProductFactory $productFactory,
       \Magento\Catalog\Api\CategoryLinkManagementInterface  $categoryLinkManagementInterface
   )
   {
       ...
       $this->categoryLinkManagementInterface = $categoryLinkManagementInterface;
   }

Step 3: Add the product to the new category. 

Note: $categoryId = [42] is the array of category ID that we use for this example

public function execute(Observer $observer)
   {
       $data = $this->request->getParams();
       $id = $data['id'];
       $product = $this->productFactory->create()->load($id);
       $categoryId = [42];
       $categoryIds = array_unique(
           array_merge(
               $product->getCategoryIds(),
               $categoryId
    public function execute(Observer $observer)
   {
       $data = $this->request->getParams();
       $id = $data['id'];
       $product = $this->productFactory->create()->load($id);
       $categoryId = [42];
       $categoryIds = array_unique(
           array_merge(
               $product->getCategoryIds(),
               $categoryId
           )
       );
       $this->categoryLinkManagementInterface->assignProductToCategories(
           $product->getSku(),
           $categoryIds
       );
   }

assignProductToCategories() will replace the existing categories list – therefore we have to add our category to the existing list, before assigning this list to the product.

See more herehttps://magenest.com/en/how-to-link-products-to-categories-in-magento-2-programmatically/

Comments

Popular posts from this blog

TOP 7 ECOMMERCE PLATFORMS TO CONSIDER IN 2023

The last few years have witnessed the rise of the eCommerce platform with tons of features and look that suit each business’s requirements for   eCommerce websites . An eCommerce platform makes it possible for businesses to reach customers in online channels, hence helping increase the market size of the businesses.  While traditional eCommerce software is costly, not scalable, difficult to work with, and time-consuming considering customization and integration with other systems, the eCommerce platform is a better solution for creating relevant, engaging, and personalized online experiences. Among hundreds of eCommerce websites, you have to pick one that can decide the future of your business. In this article, we’ll explore 7 of the best eCommerce platforms and also cover their features, pros, cons, and whom they’re recommended for most, so take a look below, you can have all the key details and see which is a perfect fit for your unique business needs. 7 Best eCommerce platf...

HONEST MAGENTO 2 REVIEW FOR ALL ECOMMERCE MERCHANTS

Ecommerce has had a significant impact on the way businesses do business. Nowadays, you can do the majority of your business tasks with a few clicks of the mouse or a few taps on your mobile device. While there are many big players in e-commerce or e-business, Magento 2 has been the front runner in the online business world – all due to the number of good things it offers. However, at some point, the average person is going to hit a wall. In today’s article, we’re going to focus on compiling a list of Magento 2 reviews so that you can learn everything about the platform from its background to key features, pros, and cons and decide whether you’d want Magneto for your e-commerce or not. What is Magento 2 platform? For online retailers, Magento is the most popular e-commerce platform. It is a high-performance, scalable solution with robust out-of-the-box capabilities and a big community of developers who are constantly adding new features to the platform. Magento 2 is the compan...

HOW TO JOIN TABLES PROGRAMMATICALLY IN MAGENTO 2

Today we talk about How to join tables programmatically in Magento 2. Sometimes you need to get join collection with product collection data or category collection data or order collection or custom table collection. In order to make you do that with ease, the developer team from Magenest recommends the topic join tables in Magento2. Here we go. How to join tables in SQL? A SQL Join statement is used to combine data or rows from two or more tables based on a common field between them. Different types of Joins are: INNER JOIN : Returns records that have matching values in both tables. LEFT JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT JOIN : Returns all records from the right table, and the matched records from the left table. FULL JOIN : Returns all records from both tables. ( we don’t use this much) For this sample, we have the following tables: Director_id Name 1 Magenest director 2 Magenest 3 Son Tung 4 Cris 5 Magento2 Magenest_d...