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

10+ BEST ECOMMERCE WEBSITE BUILDER FOR SMALL BUSINESS TO CHECK OUT

  Small businesses need to find an eCommerce website builder that is affordable and easy to use. In this blog post, we will recommend the best eCommerce website builder for small business. We will also provide a few tips on how to get started. So, if you are looking for a good eCommerce website builder, you have come to the right place! Keep reading for more information. How to find the best eCommerce website builder for small business Depending on your demands, the best option for you will vary. For example, the modest online shop offering handmade goods is going to have different needs than the seven-figure dropship business. Despite these variations, the following standards should always be taken into account when choosing a platform: Ease of use You might have little to no experience constructing websites if this is your first attempt at an eCommerce site. A site from scratch can be challenging to build if you have no experience with coding or web design. The best eCommerce web...

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...

The Top 10 Successful Shopify Stores in Australia and the Valuable Lessons They Offer

  In recent years, the eCommerce landscape has seen remarkable growth, particularly in Australia, where online businesses have flourished. Among the various platforms empowering entrepreneurs, Shopify stands out as a popular choice for Australian retailers. With its user-friendly interface, customizable designs, and a plethora of features, Shopify facilitates the creation of compelling online stores, enabling seamless connections with customers. This article dives into some of Australia's top Shopify stores, spotlighting their exceptional customer experiences, unique selling propositions, and the lessons we can glean from their triumphs. Whether you're an aspiring business owner or an enthusiastic online shopper, these stores serve as inspirational examples, showcasing how to thrive in the competitive realm of Australian eCommerce. Let's explore these captivating success stories and uncover the strategies that underpin their achievements. Leading Shopify Stores in Australia...