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.
<?php
set_time_limit(0);
ini_set('display_errors', 1);
ini_set('memory_limit', -1);
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstraps = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstraps->getObjectManager();
deleteAllProducts($objectManager);
function deleteAllProducts($objectManager) {
$objectManager->get('MagentoFrameworkRegistry')->register('isSecureArea', true);
$attrSetName = 'Dress'; // Atribute set name
$attribute_set_factoryCollection = $objectManager->get('MagentoEavModelResourceModelEntityAttributeSetCollectionFactory');
$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('MagentoCatalogModelResourceModelProductCollectionFactory');
$collection = $productCollection->create()->addAttributeToSelect('*')->addFieldToFilter('attribute_set_id',$attribute_set_id)->load();
$app_state = $objectManager->get('MagentoFrameworkAppState');
$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.

