3

How can I remove existing and assign new categories to product programmatically in magento 2 while updating product data.

 <?php

 $newCategoryIds = array(5,6);

 $existingProductId = 25;

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

 $_product = $objectManager->create('Magento\Catalog\Model\Product')->load($existingProductId);

 $_product->setName('New name xyz'); // Name of Product

 $existing = $_product->getCategoryIds(); 

 print_r($existing);// Return existing assign categories like Array(3,4)

 $_product->setCategoryIds([]); // Want to remove existing categories so i can assign updated categories but its not working

 $_product->save();

 $_product->setCategoryIds($newCategoryIds); // It's also not remove existing categories.

 $_product->save();
1

This worked for me

\Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkManagementInterface
   /**
     * Assign product to category.
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param array                          $categoryIds
     *
     * @return void
     */
    public function assignProductToCategory($product, $categoryIds = [])
    {
        if (!empty($categoryIds)) {
            $this->categoryLinkManagementInterface->assignProductToCategories(
                $product->getSku(),
                $categoryIds
            );
        }
    }

So new array wipes out existing values.

1

I tried both given solution but none of them work for me. Although both answer were correct. Actually i was updating categories of product before saving products data $_product->save(); of same product.

<?php

 $newCategoryIds = array(5,6);

 $existingProductId = 25;

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

 $_product = $objectManager->create('Magento\Catalog\Model\Product')->load($existingProductId);

 $_product->setName('New name xyz'); // Name of Product

 $_product->save();


/*
* Manage Product Categories after product save (While you are running script to update products)
* */

$categoryLinkManagementInterface = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$categoryLinkManagementInterface->assignProductToCategories($_product->getSku(), $newCategoryIds);
4
  • Where is delete?? and you d'ont tell us that youre product aren't saved Jul 3 '19 at 16:32
  • @MohamedElMrabet function assignProductToCategories will removed existing categories automatically and add new one. I have clearly says that while product is updating. Please check my question code and also before assigning categories i am saving products as well.
    – Nadeem0035
    Jul 4 '19 at 6:13
  • Ok but in this case you must change the title of your question. For other user id they have a same case ok Jul 5 '19 at 7:17
  • To do after the product save method. Thank you.
    – Jakk64
    Dec 9 '19 at 15:47
0

Assign Products to Category programmatically

<?php
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$CategoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');

$category_ids = array('22','23');
$sku = '24';

$CategoryLinkRepository->assignProductToCategories($sku, $category_ids);
?>

Remove Products from Category programmatically

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$CategoryLinkRepository = $objectManager->get('\Magento\Catalog\Model\CategoryLinkRepository');

$categoryId = 22;
$sku = '24';

$CategoryLinkRepository->deleteByIds($categoryId,$sku);
?>
1
  • Keep in mind; Do not use the objectmanager directly.
    – Prometheus
    Jul 5 '19 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.