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.
Please follow the below methods to get the attribute options...
Update product attribute value programmatically in Magento 2 . [crayon-62877875b5e6b941585513/]...
If you want restrict customer to checkout based on your...
Sometime we need to set html data without load or...
If you want get query string params in controller file,...