Magento 2 delete all products
In this tutorial I show you how to delete all products under Magento 2. In my previous article I showed how to get products by id. I also introduced you to factory pattern and repository pattern. This article is based on that information.
Magento 2 delete all products
Deleting products is a less common task. In products systems you not find it anywhere. But if you are on a development system and you are working on a product import, that may be needed. This small piece of code shows you how to delete nearly all products:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $collection = $this->_productCollectionFactory->create(); $collection->addAttributeToSelect('*'); $collection->load(); $skipSku = "Testproduct"; $length = strlen($needle); $this->_registry->register("isSecureArea", true); foreach($collection as $product) { if(substr($product->getSku(), 0, $length) === $skipSku) { //echo $product->getSku()."\n"; } else { $this->_productRepository->deleteById($product->getSku()); } } |
In the first three lines of code we get a collection of all products in our shop. In the following foreach loop we delete all of them by calling deleteById function from our product repository (in my last article I showed you how to inject this).
The important line is: $this->_registry->register("isSecureArea", true);
Magento 2 defines secure areas if you want to do critical stuff like deleting objects. If you miss that, nothing will happen.
I added an additional if statement to filter some products that should not be deleted. For my system that are all products that have a SKU like “Testproduct”. So all these products are not deleted.
How to get product collection factory
To run this script we need to inject ProductCollectionFactory, so we have to modify our __construct function with the following lines of code:
1 2 3 4 5 6 7 8 9 | protected $_productCollectionFactory; ... public function __construct( ... \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, ...) { ... $this->_productCollectionFactory = $productCollectionFactory; } |
Conclusion
For a production environment it is not a safe option to include a delete all products skript. For your development system this may be a good idea. If you are working on an import module, that is a good option to reset your store.