1

I am trying to make script to unassign category from product while save or update product. but its not working properly.

ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);

// Increase memory limit
ini_set('memory_limit', '1024M');

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';


$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();


$appState = $obj->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');


$pid = 528;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('\Magento\Catalog\Model\Product')->load($pid);
$_product->setCategoryIds('')->save();

Does anyone know another way for it? except direct query.

2

Remove a product from a category:

If you want to remove a product from a category then you can use below solution:

$categoryId = 12 ; // Category id 
$pid = 150; // Product Id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('\Magento\Catalog\Model\Product')->load($pid);
$CategoryLinkRepository =  $objectManager->get('Magento\Catalog\Api\CategoryLinkRepositoryInterface');
$CategoryLinkRepository->deleteByIds($categoryId, $productSku);

Remove all categories from a product:

Then try this:

$pid = 150; // Product Id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('\Magento\Catalog\Model\Product')->load($pid);
$CategoryLinkRepository =  $objectManager->get('Magento\Catalog\Api\CategoryLinkRepositoryInterface');
$productSku = $_product->getSku();

// all catgeories of a category
$currentCategories  = $_product->getCategoryIds();
  foreach ($currentCategories as $categoryId) {
            $CategoryLinkRepository ->deleteByIds($categoryId, $productSku);
 }
// reindex a product in magento                 

$productCategoryIndexer = $objectManager
                            ->get('Magento\Framework\Indexer\IndexerRegistry')
                            ->get(Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID);              
$productCategoryIndexer->reindexRow($_product->getId());    
  • How can i do it by CSV in Multi store – zus Dec 21 '17 at 10:53
  • While trying to unassigned the categories mannually ,when product edit, it is not working – Jaisa Apr 2 at 12:35

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.