Question

how can I delete specific categories for a product in Magento 2.Forex: I have a product with a,b,c categories, I have some conditions if the conditions meet my categories remains same but if those conditions fail I need to remove b, the category only not a,c categories. How can I achieve that?

Was it helpful?

Solution

You can do it with n98-magerun2 if this is a one-shot task:

If you want to delete categories with IDs 1, 2, 3, 4

$di->configure($di->get(\Magento\Framework\ObjectManager\ConfigLoaderInterface::class)->load('admin'))
$di->get(\Magento\Framework\Registry::class)->register('isSecureArea', true);


$cr = $di->get(\Magento\Catalog\Model\CategoryRepository::class);

$cr->get(1)->delete();
$cr->get(2)->delete();
$cr->get(3)->delete();
$cr->get(4)->delete();

OTHER TIPS

You need to build a category collection of the categories you want to delete.

Then it's just the case of something like this:

try {
    $category->delete();
    echo 'Category Removed';
  } catch (Exception $e) {
    echo 'Failed to remove category ' . $category->getId();
    echo $e->getMessage();
  }

I cant be more specific without knowing more about the conditions which means delete.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top