2

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

3

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';   // use '../app/bootstrap.php' if your root dir is pub

$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.

| improve this answer | |
0

I made some changes to the original script from @Kishor Thummar to improve performance and to log information while the script is running. You have to put the script in your webroot which is pub if you configured your server properly.

<?php

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

use Magento\Framework\App\Bootstrap;
require '../app/bootstrap.php';  // use "app/bootstrap.php" if your root is not set to pub folder (it should be though!)

$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);

$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test_debug.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info("Script started.");

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

$categoryId = 3; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);

// Set filter, so that only configurable products are collected (faster).
$categoryProducts = $category->getProductCollection()
                             ->addAttributeToSelect('*')
                             ->addAttributeToFilter('type_id', array('eq' => 'configurable'));   

foreach ($categoryProducts as $product) {
    $logger->info($product->getName());
    $_configChild = $product->getTypeInstance()->getUsedProductIds($product);
    foreach ($_configChild as $childId){
        //Delete child products
        $childProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($childId);   
        $childProduct->delete();
        $logger->info("Child simple deleted - '". $childProduct->getName());
    }

    //Delete Configurable product
    $configurableProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product->getId());
    $configurableProduct->delete();
    $logger->info('Configurable deleted - '.$configurableProduct->getName());
}

$logger->info("Script finished.");

Now you can run the script and watch the logfile with tail -f var/log/test_debug.log

| improve this answer | |
  • 1
    what is the use of else condition? – Rohan Hapani 15 hours ago
  • 1
    @RohanHapani, sorry, forgot to remove it. Thank you for the hint! – Black 15 hours ago

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.