In this guide, I am going to show you, how to remove the product of a particular attribute set in Magento 2 programmatically?
First of all, you have to create a file called “deleteProducts.php” on Magento 2 root directory.
And then paste the below code into that file.
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 41 42 43 44 |
<?php set_time_limit(0); ini_set('display_errors', 1); ini_set('memory_limit', -1); use \Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstraps = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstraps->getObjectManager(); deleteAllProducts($objectManager); function deleteAllProducts($objectManager) { $objectManager->get('\Magento\Framework\Registry')->register('isSecureArea', true); $attrSetName = 'Dress'; // Atribute set name $attribute_set_factoryCollection = $objectManager->get('\Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory'); $attribute_set_collection = $attribute_set_factoryCollection->create(); $attribute_set_collection ->addFieldToFilter('entity_type_id',4) ->addFieldToFilter('attribute_set_name',$attrSetName); $att_set = current($attribute_set_collection->getData()); $attribute_set_id = $att_set["attribute_set_id"]; $productCollection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $collection = $productCollection->create()->addAttributeToSelect('*')->addFieldToFilter('attribute_set_id',$attribute_set_id)->load(); $app_state = $objectManager->get('\Magento\Framework\App\State'); $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; } } } |
And now you can run this file through cronjob and URL.
So the URL will be like this : http://yourdomainname/deleteProducts.php
That’s it.
I hope my post is helpful. If you still need any assistance about that, please comment below.
[crayon-63d3e77be66cd189694691/] Using above fucntion Images can be imported directly from...
Override view block using di.xml and add the below code...
You can check a list of called layout XML for...
Follow the below steps to install and set up PWA...
If you want to remove all leading zero's from order,...
Let our Magento expert connect to discuss your requirement.
We offer Magento
certified developers.
Our Magento clientele
is 500+.
We sign NDA for the
security of your projects.
We’ve performed 100+
Magento migration projects.
Free quotation
on your project.
Three months warranty on
code developed by us.