Tutorialsplane

Magento 2 Delete Products programmatically


Magento 2 Delete Products programmatically | PHP Script– You can delete products programmatially in using product id. Here in this tutorial we are going to explain how you can delete the products using your own program.


Magento 2 Delete Products programmatically | Delete All Products Script Example

Now let us go to understand how to deal with product deletion in Magento 2-

Delete Product By Id

To delete single product by id first load product object by id then you can delete it as below-

Magento 2 Delete Products programmatically Example:

$productID = 999;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product->load($productID)->delete();

Delete All Products

Let us create simple script to delete products. If you want to delete all products then you need to load products collection and delete products one by one simply as below-

Delete All Products Example:

$objectManager->get('Magento\Framework\Registry')->register('isSecureArea', true);
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()->addAttributeToSelect('*')->load();
$app_state = $objectManager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');

foreach ($collection as $product){
    try {
        echo 'Deleted '.$product->getName()."<br/>";
        $product->delete();

    } catch (Exception $e) {
        echo 'Unable to delete product '.$product->getName()."<br/>";
        echo $e->getMessage() . "<br/>";
    }   
}