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 here: https://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...

TOP 10 BEST B2B ECOMMERCE WEBSITES: SECRETS BEHIND THE SUCCESS

Many entrepreneurs start looking for eCommerce solutions when they are tired of having to meet face-to-face with customers or suppliers. According to the U.S. Census Bureau data, international trade totals around $4 trillion per year. However, with everything available online, it’s reasonable to think that number would be much higher if not for distance barriers between buyers and sellers. When building an attractive site as one of the best B2B eCommerce websites, you’ll need to choose an appropriate   eCommerce platform , high-quality content on your product pages, well-written copy for your about page, and a memorable domain and attractive design.  You can always fall back on a platform like Magento and Shopify to help you with the basics. But what if you want an engaging eCommerce site? Here are the top 10 best B2B eCommerce Websites that will inspire your next project. The 10 Best B2B eCommerce Websites #  Quill Quill, which Staples own, is the lar...

HOW MUCH DOES MAGENTO 2 COST? WHAT IS THE INVESTMENT EXPENSE FOR A PROPER MAGENTO 2 SYSTEM

Magento 2 is still a popular eCommerce platform, and in this Magento pricing guide, we’ll go through how much does Magento 2 cost to establish and manage a Magento store. Among a number of eCommerce platforms, Magento will not disappoint you with a wide range of functionalities, enhanced security mechanisms, and, most importantly, completely free customisation. Many merchants, though, wonder, “How much does Magento cost?” This includes the fees of purchasing a license, hosting alternatives, and other necessities for running a successful Magento store. What is Magento 2? Magento 2 is an open-source e-commerce platform developed by Varien Inc’s Roy Rubin and Yoav Kutner. Magento was first made available on March 31, 2007. It is a handy software for online businesses and the world’s largest E-commerce platform. Because of its sophisticated, scalable architecture, Magento 2 is the most popular CMS (Content Management System) for creating online stores all over the world. It is compatible w...