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.


delete_magento_2_products_programmatically

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

<?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;
        }   
    }      
}

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 *

*