3

Need a script where current existing products needs to unlink and link to other categories. let me know the process also

2 Answers 2

2

Following is the code you will use in order to assign and unassign categories from product

 //Object Manager instance
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

//Product repository interface
 $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

//Load Product - assuming we have product id only
 $product = $objectManager->create('Magento\Catalog\Model\Product')->load( $product_id );

$category_id = '34'; //Replace category id here

$product->setCategoryIds( array($category_id) ); //It accepts array so we can add multiple category ids.

try {
 $productRepository->save($product);
 } catch (\Exception $e) {
 // Handle error
 }

I hope this will help

2
3

Use below code to assign:

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

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

$category_ids = array('101','102');
$sku = '24-MB01';

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

And below to remove:

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

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

  $categoryId = 101;
  $sku = '24-MB01';

  $CategoryLinkRepository->deleteByIds($categoryId,$sku);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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