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.

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

$objectManager = MagentoFrameworkAppObjectManager::getInstance();

function deleteAllProducts($objectManager) {

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

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

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

Share this Tutorial