Delete magento 2 products programmatically

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.

Please click here to refer the tutorial that explains how to create attribute options programmatically and other magento tutorials.


  • Initialise script
  • Delete magento 2 products

Initialise script

As the first step create the deleteproducts.php file inside the script folder in the magento root directory.

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;

Please also refer the other tutorial which explains how import to product programmatically and delete the categories programmatically.

If you have any further queries please leave a reply

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *