Remove magento 2 products script

This tutorial explains how to delete magento 2 products programmatically. If you want delete all the products in magento 2 at one go use the following code.

Here it gives the step by step explanation of how to create the file, connect to magento database externally and delete the products programmatically.

<?php
use MagentoFrameworkAppBootstrap;
include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = MagentoFrameworkAppObjectManager::getInstance();
deleteAllProducts($objectManager);

function deleteAllProducts($objectManager) {

    $objectManager->get('MagentoFrameworkRegistry')->register('isSecureArea', true);
    $productCollection = $objectManager->create('MagentoCatalogModelResourceModelProductCollectionFactory');
    $collection = $productCollection->create()->addAttributeToSelect('*')->load();
    $app_state = $objectManager->get('MagentoFrameworkAppState');
    $app_state->setAreaCode('frontend');

    foreach ($collection as $product){
        try {
            echo 'Deleted '.$product->getName().PHP_EOL;
            $product->delete();

        } catch (Exception $e) {
            echo 'Failed to remove product '.$product->getName() .PHP_EOL;
            echo $e->getMessage() . "n" .PHP_EOL;
        }   
    }      
}

Share this Tutorial