In this blog, we are going to explain how to Delete Products programmatically in Magento 2.
Delete Product By Id or SKU:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php use Magento\Framework\AppInterface; try { require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('\Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository'); $registry = $objectManager->get('\Magento\Framework\Registry'); $registry->register('isSecureArea', true); //There are two ways to remove products using SKU or product id. // using sku to remove product $prosku="wt-MB01"; $productRepository->deleteById($prosku); //using product id to remove product $product_id = 1; //here your product id $product = $productRepository->getById($product_id); $productRepository->delete($product); echo $prosku." Your Product Remove Successfully."; } catch(\Exception $e) { print_r($e->getMessage()); } |
Delete All Products:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$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>"; } } |
Thank You!
Hit 5 Stars if you find this post helpful
0 (based on 0 Reviews)