Assign products to category programatically in magento2 Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Adding Product to Category on selecting yes/no attribute in Magento 2Assign product to category programmatically Magento2 receive an errorHow to assign category on multiple products?Assign products to a category that are not assigned to any categoryProgrammatically assign a product's categories _AND_ sort order/positionFind all Simple Products without category. Assign Cat to simple Product who is child of configurableHow to assign category to all subcategory products?How to assign categories to a new product automatically?Add collection of products to a categoryProducts not getting displayed on category page in magento 2Assign Products created in last 45 days to specific categoryMagento2: Assign products to category programatically

Disembodied hand growing fangs

How does Python know the values already stored in its memory?

Significance of Cersei's obsession with elephants?

AppleTVs create a chatty alternate WiFi network

What initially awakened the Balrog?

ArcGIS Pro Python arcpy.CreatePersonalGDB_management

Hangman Game with C++

Is it fair for a professor to grade us on the possession of past papers?

How to tell that you are a giant?

Do wooden building fires get hotter than 600°C?

How to compare two different files line by line in unix?

Can anything be seen from the center of the Boötes void? How dark would it be?

Drawing without replacement: why is the order of draw irrelevant?

How does the secondary effect of the Heat Metal spell interact with a creature resistant/immune to fire damage?

Using audio cues to encourage good posture

Is there a kind of relay that only consumes power when switching?

Why do we need to use the builder design pattern when we can do the same thing with setters?

Sum letters are not two different

How do I find out the mythology and history of my Fortress?

How does light 'choose' between wave and particle behaviour?

Is a ledger board required if the side of my house is wood?

Dating a Former Employee

What is this clumpy 20-30cm high yellow-flowered plant?

How much damage would a cupful of neutron star matter do to the Earth?



Assign products to category programatically in magento2



Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Adding Product to Category on selecting yes/no attribute in Magento 2Assign product to category programmatically Magento2 receive an errorHow to assign category on multiple products?Assign products to a category that are not assigned to any categoryProgrammatically assign a product's categories _AND_ sort order/positionFind all Simple Products without category. Assign Cat to simple Product who is child of configurableHow to assign category to all subcategory products?How to assign categories to a new product automatically?Add collection of products to a categoryProducts not getting displayed on category page in magento 2Assign Products created in last 45 days to specific categoryMagento2: Assign products to category programatically



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








7















How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.










share|improve this question






























    7















    How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.










    share|improve this question


























      7












      7








      7


      2






      How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.










      share|improve this question
















      How can I assign 'New products' to 'NEW PRODUCTS category' programatically in magento 2.







      magento2 product category






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 2 '18 at 10:32









      Teja Bhagavan Kollepara

      2,99241949




      2,99241949










      asked Oct 14 '16 at 10:03









      chinchuchinchu

      6527




      6527




















          4 Answers
          4






          active

          oldest

          votes


















          14














          You need to get category Ids and product Id to set data:
          impliment this :



          $this->getCategoryLinkManagement()->assignProductToCategories(
          $product->getSku(),
          $product->getCategoryIds()
          );


          also impliment this function :



          private function getCategoryLinkManagement()

          if (null === $this->categoryLinkManagement)
          $this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
          ->get('MagentoCatalogApiCategoryLinkManagementInterface');

          return $this->categoryLinkManagement;



          rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface



          intialize :



          protected $categoryLinkManagement;




          Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor








          share|improve this answer

























          • I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?

            – chinchu
            Oct 17 '16 at 9:58











          • Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?

            – Ronak Chauhan
            Oct 17 '16 at 12:40











          • Yes, I have added. I worked fine.

            – chinchu
            Oct 18 '16 at 8:48











          • Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..

            – Daniel_12
            Oct 30 '18 at 15:18











          • @Daniel_12 are you getting any error?

            – Ronak Chauhan
            Oct 30 '18 at 17:24


















          4














          I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.



          In your constructor, inject the CategoryLinkManagementInterface:



          protected $categoryLinkManagement;

          public function __construct(
          ...
          MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
          ...
          )
          $this->categoryLinkManagement = $categoryLinkManagementInterface;
          ...



          Later in your code, assign categories the following way:



          $product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
          $categoryIds = [
          42,
          606
          ];
          $this->categoryLinkManagement->assignProductToCategories(
          $product->getSku(),
          $categoryIds
          );


          This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:



          $categoryIds = array_unique(
          array_merge(
          $product->getCategoryIds(),
          $categoryIds
          )
          );


          Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()



          $product = $this->productRepository->save($product);


          the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,



          $product = $this->productRepository->getById($product->getId());


          right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again



          $product->setCategoryIds($categoryIds);


          If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.






          share|improve this answer























          • hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,

            – jafar pinjar
            Nov 26 '18 at 11:59











          • Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8

            – T. Dreiling
            Nov 27 '18 at 12:07












          • 1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?

            – jafar pinjar
            Nov 27 '18 at 12:18











          • 1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.

            – T. Dreiling
            Nov 27 '18 at 12:53











          • The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id

            – jafar pinjar
            Nov 27 '18 at 13:22



















          1














          Assign Products To Category



           <?php
          $new_category_id = array('100','101');
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
          $CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);


          Remove Products From Category



           <?php
          $category_id = 101;
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
          $CategoryLinkRepository->deleteByIds($category_id ,$sku);





          share|improve this answer

























          • getting this error, Could not save product with position 0 to category 8

            – jafar pinjar
            Nov 24 '18 at 10:49











          • @jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution

            – chirag dodia
            Nov 26 '18 at 3:57











          • hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used

            – jafar pinjar
            Nov 26 '18 at 6:00











          • @jafarpinjar try with fresh product and check is this something related to a particular product?

            – chirag dodia
            Nov 26 '18 at 11:52











          • hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8

            – jafar pinjar
            Nov 26 '18 at 11:55


















          -1














          $objectManager = ObjectManager::getInstance();
          $catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
          $catalogProduct->setSku('sku-1');
          $catalogProduct->setName('name');
          $catalogProduct->setAttributeSetId(4);
          $catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
          $catalogProduct->setVisibility(4);
          $catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
          $catalogProduct->setPrice(100);

          $catalogProduct->setCategoryIds(['id']); // here you are

          $catalogProduct->setStockData([
          'is_in_stock' => true,
          'qty' => 10
          ]);

          $catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
          $catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()

          $catalogProduct->save();





          share|improve this answer























          • This is a very heavy request and executes very slowly as oppose to Link Manager

            – Timik
            Aug 16 '18 at 18:53











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "479"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f140875%2fassign-products-to-category-programatically-in-magento2%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          14














          You need to get category Ids and product Id to set data:
          impliment this :



          $this->getCategoryLinkManagement()->assignProductToCategories(
          $product->getSku(),
          $product->getCategoryIds()
          );


          also impliment this function :



          private function getCategoryLinkManagement()

          if (null === $this->categoryLinkManagement)
          $this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
          ->get('MagentoCatalogApiCategoryLinkManagementInterface');

          return $this->categoryLinkManagement;



          rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface



          intialize :



          protected $categoryLinkManagement;




          Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor








          share|improve this answer

























          • I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?

            – chinchu
            Oct 17 '16 at 9:58











          • Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?

            – Ronak Chauhan
            Oct 17 '16 at 12:40











          • Yes, I have added. I worked fine.

            – chinchu
            Oct 18 '16 at 8:48











          • Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..

            – Daniel_12
            Oct 30 '18 at 15:18











          • @Daniel_12 are you getting any error?

            – Ronak Chauhan
            Oct 30 '18 at 17:24















          14














          You need to get category Ids and product Id to set data:
          impliment this :



          $this->getCategoryLinkManagement()->assignProductToCategories(
          $product->getSku(),
          $product->getCategoryIds()
          );


          also impliment this function :



          private function getCategoryLinkManagement()

          if (null === $this->categoryLinkManagement)
          $this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
          ->get('MagentoCatalogApiCategoryLinkManagementInterface');

          return $this->categoryLinkManagement;



          rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface



          intialize :



          protected $categoryLinkManagement;




          Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor








          share|improve this answer

























          • I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?

            – chinchu
            Oct 17 '16 at 9:58











          • Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?

            – Ronak Chauhan
            Oct 17 '16 at 12:40











          • Yes, I have added. I worked fine.

            – chinchu
            Oct 18 '16 at 8:48











          • Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..

            – Daniel_12
            Oct 30 '18 at 15:18











          • @Daniel_12 are you getting any error?

            – Ronak Chauhan
            Oct 30 '18 at 17:24













          14












          14








          14







          You need to get category Ids and product Id to set data:
          impliment this :



          $this->getCategoryLinkManagement()->assignProductToCategories(
          $product->getSku(),
          $product->getCategoryIds()
          );


          also impliment this function :



          private function getCategoryLinkManagement()

          if (null === $this->categoryLinkManagement)
          $this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
          ->get('MagentoCatalogApiCategoryLinkManagementInterface');

          return $this->categoryLinkManagement;



          rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface



          intialize :



          protected $categoryLinkManagement;




          Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor








          share|improve this answer















          You need to get category Ids and product Id to set data:
          impliment this :



          $this->getCategoryLinkManagement()->assignProductToCategories(
          $product->getSku(),
          $product->getCategoryIds()
          );


          also impliment this function :



          private function getCategoryLinkManagement()

          if (null === $this->categoryLinkManagement)
          $this->categoryLinkManagement = MagentoFrameworkAppObjectManager::getInstance()
          ->get('MagentoCatalogApiCategoryLinkManagementInterface');

          return $this->categoryLinkManagement;



          rest dependency you should manage for : MagentoCatalogApiCategoryLinkManagementInterface



          intialize :



          protected $categoryLinkManagement;




          Direct use of MagentoFrameworkAppObjectManager::getInstance() is not valid as per magento so you can inject it in Constructor









          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 26 '17 at 6:18

























          answered Oct 14 '16 at 10:21









          Ronak ChauhanRonak Chauhan

          4,28411550




          4,28411550












          • I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?

            – chinchu
            Oct 17 '16 at 9:58











          • Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?

            – Ronak Chauhan
            Oct 17 '16 at 12:40











          • Yes, I have added. I worked fine.

            – chinchu
            Oct 18 '16 at 8:48











          • Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..

            – Daniel_12
            Oct 30 '18 at 15:18











          • @Daniel_12 are you getting any error?

            – Ronak Chauhan
            Oct 30 '18 at 17:24

















          • I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?

            – chinchu
            Oct 17 '16 at 9:58











          • Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?

            – Ronak Chauhan
            Oct 17 '16 at 12:40











          • Yes, I have added. I worked fine.

            – chinchu
            Oct 18 '16 at 8:48











          • Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..

            – Daniel_12
            Oct 30 '18 at 15:18











          • @Daniel_12 are you getting any error?

            – Ronak Chauhan
            Oct 30 '18 at 17:24
















          I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?

          – chinchu
          Oct 17 '16 at 9:58





          I used this code in a block and tried to render that block in template file. When I tried this method I got "Uncaught Error: Call to a member function assignProductToCategories()" in the template file. Could you please help me to sort out this?

          – chinchu
          Oct 17 '16 at 9:58













          Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?

          – Ronak Chauhan
          Oct 17 '16 at 12:40





          Have you give dependency for "MagentoCatalogApiCategoryLinkManagementInterface" ?

          – Ronak Chauhan
          Oct 17 '16 at 12:40













          Yes, I have added. I worked fine.

          – chinchu
          Oct 18 '16 at 8:48





          Yes, I have added. I worked fine.

          – chinchu
          Oct 18 '16 at 8:48













          Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..

          – Daniel_12
          Oct 30 '18 at 15:18





          Hi @RonakChauhan I tried your code but it doesnt seem like working . My products are not getting assigned to category..

          – Daniel_12
          Oct 30 '18 at 15:18













          @Daniel_12 are you getting any error?

          – Ronak Chauhan
          Oct 30 '18 at 17:24





          @Daniel_12 are you getting any error?

          – Ronak Chauhan
          Oct 30 '18 at 17:24













          4














          I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.



          In your constructor, inject the CategoryLinkManagementInterface:



          protected $categoryLinkManagement;

          public function __construct(
          ...
          MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
          ...
          )
          $this->categoryLinkManagement = $categoryLinkManagementInterface;
          ...



          Later in your code, assign categories the following way:



          $product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
          $categoryIds = [
          42,
          606
          ];
          $this->categoryLinkManagement->assignProductToCategories(
          $product->getSku(),
          $categoryIds
          );


          This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:



          $categoryIds = array_unique(
          array_merge(
          $product->getCategoryIds(),
          $categoryIds
          )
          );


          Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()



          $product = $this->productRepository->save($product);


          the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,



          $product = $this->productRepository->getById($product->getId());


          right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again



          $product->setCategoryIds($categoryIds);


          If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.






          share|improve this answer























          • hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,

            – jafar pinjar
            Nov 26 '18 at 11:59











          • Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8

            – T. Dreiling
            Nov 27 '18 at 12:07












          • 1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?

            – jafar pinjar
            Nov 27 '18 at 12:18











          • 1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.

            – T. Dreiling
            Nov 27 '18 at 12:53











          • The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id

            – jafar pinjar
            Nov 27 '18 at 13:22
















          4














          I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.



          In your constructor, inject the CategoryLinkManagementInterface:



          protected $categoryLinkManagement;

          public function __construct(
          ...
          MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
          ...
          )
          $this->categoryLinkManagement = $categoryLinkManagementInterface;
          ...



          Later in your code, assign categories the following way:



          $product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
          $categoryIds = [
          42,
          606
          ];
          $this->categoryLinkManagement->assignProductToCategories(
          $product->getSku(),
          $categoryIds
          );


          This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:



          $categoryIds = array_unique(
          array_merge(
          $product->getCategoryIds(),
          $categoryIds
          )
          );


          Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()



          $product = $this->productRepository->save($product);


          the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,



          $product = $this->productRepository->getById($product->getId());


          right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again



          $product->setCategoryIds($categoryIds);


          If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.






          share|improve this answer























          • hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,

            – jafar pinjar
            Nov 26 '18 at 11:59











          • Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8

            – T. Dreiling
            Nov 27 '18 at 12:07












          • 1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?

            – jafar pinjar
            Nov 27 '18 at 12:18











          • 1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.

            – T. Dreiling
            Nov 27 '18 at 12:53











          • The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id

            – jafar pinjar
            Nov 27 '18 at 13:22














          4












          4








          4







          I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.



          In your constructor, inject the CategoryLinkManagementInterface:



          protected $categoryLinkManagement;

          public function __construct(
          ...
          MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
          ...
          )
          $this->categoryLinkManagement = $categoryLinkManagementInterface;
          ...



          Later in your code, assign categories the following way:



          $product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
          $categoryIds = [
          42,
          606
          ];
          $this->categoryLinkManagement->assignProductToCategories(
          $product->getSku(),
          $categoryIds
          );


          This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:



          $categoryIds = array_unique(
          array_merge(
          $product->getCategoryIds(),
          $categoryIds
          )
          );


          Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()



          $product = $this->productRepository->save($product);


          the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,



          $product = $this->productRepository->getById($product->getId());


          right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again



          $product->setCategoryIds($categoryIds);


          If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.






          share|improve this answer













          I think, this needs an updated answer which does not make use of the object manager. Also, there are some kinks involved which are not mentioned anywhere.



          In your constructor, inject the CategoryLinkManagementInterface:



          protected $categoryLinkManagement;

          public function __construct(
          ...
          MagentoCatalogApiCategoryLinkManagementInterface $categoryLinkManagementInterface,
          ...
          )
          $this->categoryLinkManagement = $categoryLinkManagementInterface;
          ...



          Later in your code, assign categories the following way:



          $product = $this->productRepository->getById(1337); // or any other way to get a product model/interface
          $categoryIds = [
          42,
          606
          ];
          $this->categoryLinkManagement->assignProductToCategories(
          $product->getSku(),
          $categoryIds
          );


          This will replace all previous category assignments. If you want to keep the existing category assignments, use something like this:



          $categoryIds = array_unique(
          array_merge(
          $product->getCategoryIds(),
          $categoryIds
          )
          );


          Be aware: The link management defers the category assignment (for the product attribute) to the scheduled indexer. This means that if you make other changes to the product and save it after assignProductToCategories()



          $product = $this->productRepository->save($product);


          the category assignments will be gone as $product contains either null (if it was a newly created product) or only the previously assigned categories for its attribute. Also,



          $product = $this->productRepository->getById($product->getId());


          right after assignProductToCategories() will not help for the same reason mentioned above. Either assign categories at the latest possible point in time (when you do not save the product afterwards) or assign the attribute manually before saving again



          $product->setCategoryIds($categoryIds);


          If you opt to use the latter, you could probably fall back to only using setCategoryIds(). I have not tested either case (assignProductToCategories + setCategoryIds + save or setCategoryIds only + save) for performance impact, so I can not comment on that, but I think the whole circumstance was important to mention.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 '18 at 18:05









          T. DreilingT. Dreiling

          613




          613












          • hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,

            – jafar pinjar
            Nov 26 '18 at 11:59











          • Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8

            – T. Dreiling
            Nov 27 '18 at 12:07












          • 1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?

            – jafar pinjar
            Nov 27 '18 at 12:18











          • 1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.

            – T. Dreiling
            Nov 27 '18 at 12:53











          • The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id

            – jafar pinjar
            Nov 27 '18 at 13:22


















          • hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,

            – jafar pinjar
            Nov 26 '18 at 11:59











          • Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8

            – T. Dreiling
            Nov 27 '18 at 12:07












          • 1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?

            – jafar pinjar
            Nov 27 '18 at 12:18











          • 1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.

            – T. Dreiling
            Nov 27 '18 at 12:53











          • The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id

            – jafar pinjar
            Nov 27 '18 at 13:22

















          hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,

          – jafar pinjar
          Nov 26 '18 at 11:59





          hi, @Drelling, Could not save product "41859" with position 0 to category 8 getting above error,

          – jafar pinjar
          Nov 26 '18 at 11:59













          Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8

          – T. Dreiling
          Nov 27 '18 at 12:07






          Hi @jafarpinjar, is that all you got in terms of error messages? I could think of a few reasons, why this occured: 1. You accidentally used $product->getId() instead of $product->getSku() 2. The product's URL key is not unique (although I think that the error message would be specific) 3. The product is already assigned to category with id 8

          – T. Dreiling
          Nov 27 '18 at 12:07














          1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?

          – jafar pinjar
          Nov 27 '18 at 12:18





          1. can we not use $product->getId()? 3. The product is already assigned to category with id 8 – T. if assigned can we not remove it?

          – jafar pinjar
          Nov 27 '18 at 12:18













          1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.

          – T. Dreiling
          Nov 27 '18 at 12:53





          1. No, assignProductToCategories() explicitly needs the SKU, not the ID! If that was your error, try again with SKU instead. 3. Ah, I was somewhat wrong here. The error I was thinking of occurs when $categoryIds would contain the same category more than once. You actually need to include category id 8 to keep it in that category. If you don't, it will be removed. So that's how you can remove a product from a category.

          – T. Dreiling
          Nov 27 '18 at 12:53













          The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id

          – jafar pinjar
          Nov 27 '18 at 13:22






          The error I was thinking of occurs when $categoryIds would contain the same category more than once. Its not possible is it? because category id is unique, I am passing sku only to this method assignProductToCategories not the id

          – jafar pinjar
          Nov 27 '18 at 13:22












          1














          Assign Products To Category



           <?php
          $new_category_id = array('100','101');
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
          $CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);


          Remove Products From Category



           <?php
          $category_id = 101;
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
          $CategoryLinkRepository->deleteByIds($category_id ,$sku);





          share|improve this answer

























          • getting this error, Could not save product with position 0 to category 8

            – jafar pinjar
            Nov 24 '18 at 10:49











          • @jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution

            – chirag dodia
            Nov 26 '18 at 3:57











          • hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used

            – jafar pinjar
            Nov 26 '18 at 6:00











          • @jafarpinjar try with fresh product and check is this something related to a particular product?

            – chirag dodia
            Nov 26 '18 at 11:52











          • hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8

            – jafar pinjar
            Nov 26 '18 at 11:55















          1














          Assign Products To Category



           <?php
          $new_category_id = array('100','101');
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
          $CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);


          Remove Products From Category



           <?php
          $category_id = 101;
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
          $CategoryLinkRepository->deleteByIds($category_id ,$sku);





          share|improve this answer

























          • getting this error, Could not save product with position 0 to category 8

            – jafar pinjar
            Nov 24 '18 at 10:49











          • @jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution

            – chirag dodia
            Nov 26 '18 at 3:57











          • hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used

            – jafar pinjar
            Nov 26 '18 at 6:00











          • @jafarpinjar try with fresh product and check is this something related to a particular product?

            – chirag dodia
            Nov 26 '18 at 11:52











          • hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8

            – jafar pinjar
            Nov 26 '18 at 11:55













          1












          1








          1







          Assign Products To Category



           <?php
          $new_category_id = array('100','101');
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
          $CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);


          Remove Products From Category



           <?php
          $category_id = 101;
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
          $CategoryLinkRepository->deleteByIds($category_id ,$sku);





          share|improve this answer















          Assign Products To Category



           <?php
          $new_category_id = array('100','101');
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogApiCategoryLinkManagementInterface');
          $CategoryLinkRepository->assignProductToCategories($sku, $new_category_id);


          Remove Products From Category



           <?php
          $category_id = 101;
          $sku = 'sku of product';

          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $CategoryLinkRepository = $objectManager->get('MagentoCatalogModelCategoryLinkRepository');
          $CategoryLinkRepository->deleteByIds($category_id ,$sku);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 15 at 7:32









          Marius

          168k28324692




          168k28324692










          answered Mar 29 '18 at 7:22









          chirag dodiachirag dodia

          83931122




          83931122












          • getting this error, Could not save product with position 0 to category 8

            – jafar pinjar
            Nov 24 '18 at 10:49











          • @jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution

            – chirag dodia
            Nov 26 '18 at 3:57











          • hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used

            – jafar pinjar
            Nov 26 '18 at 6:00











          • @jafarpinjar try with fresh product and check is this something related to a particular product?

            – chirag dodia
            Nov 26 '18 at 11:52











          • hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8

            – jafar pinjar
            Nov 26 '18 at 11:55

















          • getting this error, Could not save product with position 0 to category 8

            – jafar pinjar
            Nov 24 '18 at 10:49











          • @jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution

            – chirag dodia
            Nov 26 '18 at 3:57











          • hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used

            – jafar pinjar
            Nov 26 '18 at 6:00











          • @jafarpinjar try with fresh product and check is this something related to a particular product?

            – chirag dodia
            Nov 26 '18 at 11:52











          • hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8

            – jafar pinjar
            Nov 26 '18 at 11:55
















          getting this error, Could not save product with position 0 to category 8

          – jafar pinjar
          Nov 24 '18 at 10:49





          getting this error, Could not save product with position 0 to category 8

          – jafar pinjar
          Nov 24 '18 at 10:49













          @jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution

          – chirag dodia
          Nov 26 '18 at 3:57





          @jafarpinjar this error is related to other customization. If you check this code snippet with fresh Magento install, it will work well. Please check if any third party customization preventing this code from execution

          – chirag dodia
          Nov 26 '18 at 3:57













          hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used

          – jafar pinjar
          Nov 26 '18 at 6:00





          hi @chirag dodia, no, I have used this code in custom file and running it by moving to root folder, no customization is used

          – jafar pinjar
          Nov 26 '18 at 6:00













          @jafarpinjar try with fresh product and check is this something related to a particular product?

          – chirag dodia
          Nov 26 '18 at 11:52





          @jafarpinjar try with fresh product and check is this something related to a particular product?

          – chirag dodia
          Nov 26 '18 at 11:52













          hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8

          – jafar pinjar
          Nov 26 '18 at 11:55





          hi @chirag, i got this error, Could not save product "41859" with position 0 to category 8

          – jafar pinjar
          Nov 26 '18 at 11:55











          -1














          $objectManager = ObjectManager::getInstance();
          $catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
          $catalogProduct->setSku('sku-1');
          $catalogProduct->setName('name');
          $catalogProduct->setAttributeSetId(4);
          $catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
          $catalogProduct->setVisibility(4);
          $catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
          $catalogProduct->setPrice(100);

          $catalogProduct->setCategoryIds(['id']); // here you are

          $catalogProduct->setStockData([
          'is_in_stock' => true,
          'qty' => 10
          ]);

          $catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
          $catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()

          $catalogProduct->save();





          share|improve this answer























          • This is a very heavy request and executes very slowly as oppose to Link Manager

            – Timik
            Aug 16 '18 at 18:53















          -1














          $objectManager = ObjectManager::getInstance();
          $catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
          $catalogProduct->setSku('sku-1');
          $catalogProduct->setName('name');
          $catalogProduct->setAttributeSetId(4);
          $catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
          $catalogProduct->setVisibility(4);
          $catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
          $catalogProduct->setPrice(100);

          $catalogProduct->setCategoryIds(['id']); // here you are

          $catalogProduct->setStockData([
          'is_in_stock' => true,
          'qty' => 10
          ]);

          $catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
          $catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()

          $catalogProduct->save();





          share|improve this answer























          • This is a very heavy request and executes very slowly as oppose to Link Manager

            – Timik
            Aug 16 '18 at 18:53













          -1












          -1








          -1







          $objectManager = ObjectManager::getInstance();
          $catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
          $catalogProduct->setSku('sku-1');
          $catalogProduct->setName('name');
          $catalogProduct->setAttributeSetId(4);
          $catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
          $catalogProduct->setVisibility(4);
          $catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
          $catalogProduct->setPrice(100);

          $catalogProduct->setCategoryIds(['id']); // here you are

          $catalogProduct->setStockData([
          'is_in_stock' => true,
          'qty' => 10
          ]);

          $catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
          $catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()

          $catalogProduct->save();





          share|improve this answer













          $objectManager = ObjectManager::getInstance();
          $catalogProduct = $objectManager->create('MagentoCatalogModelProduct');
          $catalogProduct->setSku('sku-1');
          $catalogProduct->setName('name');
          $catalogProduct->setAttributeSetId(4);
          $catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
          $catalogProduct->setVisibility(4);
          $catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
          $catalogProduct->setPrice(100);

          $catalogProduct->setCategoryIds(['id']); // here you are

          $catalogProduct->setStockData([
          'is_in_stock' => true,
          'qty' => 10
          ]);

          $catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
          $catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()

          $catalogProduct->save();






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 3 '18 at 12:15









          Yamen AshrafYamen Ashraf

          1794




          1794












          • This is a very heavy request and executes very slowly as oppose to Link Manager

            – Timik
            Aug 16 '18 at 18:53

















          • This is a very heavy request and executes very slowly as oppose to Link Manager

            – Timik
            Aug 16 '18 at 18:53
















          This is a very heavy request and executes very slowly as oppose to Link Manager

          – Timik
          Aug 16 '18 at 18:53





          This is a very heavy request and executes very slowly as oppose to Link Manager

          – Timik
          Aug 16 '18 at 18:53

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f140875%2fassign-products-to-category-programatically-in-magento2%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Sum ergo cogito? 1 nng

          三茅街道4182Guuntc Dn precexpngmageondP