When you need to remove a product from your Magento 2 store you can Delete products programmatically in Magento 2.
Step 1:
Create one file product_remove.php in the Magento root directory then add the below code.
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 | <?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 $sky="your sku here"; $productRepository->deleteById($sky); //using product id to remove product $product_id = 1; //here your product id $product = $productRepository->getById($product_id); $productRepository->delete($product); echo $sky." Your Product Remove Successfully."; } catch(\Exception $e) { print_r($e->getMessage()); } |
Step 2:
After adding the above code run like
https://yourdomain/product_remove.php/
Conclusion
You can now remove/Delete Product programmatically in Magento 2 and keep your products catalog up-to-date.
Comments are closed.