I want to Delete products custom options using bulk remove functionality. How I can archive that?
2 Answers
You need to do this by custom script
//$products is your products collection where custom options needs to be deleted
foreach ($products as $product) {
$product = $this->productModel->load($product->getId()); //$this->productModel is the object of \Magento\Catalog\Model\Product
if ($product->getOptions()) {
foreach ($product->getOptions() as $opt) {
$opt->delete();
}
echo $product->getId()." Options deleted";
} else {
echo $product->getId()." has no option";
}
}
You can either use it in custom script, or in admin controller, where ever you need.
Run Script in your magento2 root directory
ob_start();
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
ini_set('memory_limit', '1024M');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$products = $objectManager->get('\Magento\Catalog\Model\Product')->getCollection();
foreach ($products as $product) {
$product = $objectManager->get('\Magento\Catalog\Model\Product')->load($product->getId());
if($product->getOptions() != ”){
foreach ($product->getOptions() as $opt){
$opt->delete();
}
$product->setHasOptions(0)->save();
}
}