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


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 {
 } catch (\Exception $e) {
 // Handle error

I hope this will help

| improve this answer | |

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';

| improve this answer | |

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.