1

How to delete all configurable products with associated simple products from certain category programmatically in Magento2?

I found an old topic for Magento 1, but that’s not what I need.

I know how to remove the simple and configuration separately, but I don’t understand how to remove all the configuration products and the simples attached to them with certain category magento2

Thanks

2

Create PHP file in the Magento root directory like "deleteproducts.php". And add the below code to file.

Note: Please take a backup before running this script.

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);

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

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager->get('Magento\Framework\Registry')->register('isSecureArea', true);

$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');

$categoryId = 23; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);
$categoryProducts = $category->getProductCollection()->addAttributeToSelect('*');

foreach ($categoryProducts as $product) {
    if($product->getTypeId() == "configurable"){
        $_configChild = $product->getTypeInstance()->getUsedProductIds($product);
        foreach ($_configChild as $childId){
            //Delete child products
            $childProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($childId);
            echo 'Child simple deleted - '.$childProduct->getName()."<br>";
            $childProduct->delete();
        }
        //Delete Configurable product
        $configurableProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
        echo 'Configurable deleted - '.$configurableProduct->getName()."<br>";
        $configurableProduct->delete();
    }
}

Then run the script in the browser like yourdomain.com/deleteproducts.php

Hope it will work for you.

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.