I created magento 2 custom option programmatically like this:
$options[] = [
'title' => 'cthulu',
'type' => 'field',
'is_require' => false,
'sort_order' => 2,
'price' => 0,
'price_type' => 'fixed',
'sku' => 'cthulu',
'max_characters' => 20,
];
$options[] = [
'title' => 'comment',
'type' => 'field',
'is_require' => false,
'sort_order' => 2,
'price' => 0,
'price_type' => 'fixed',
'sku' => 'comment',
'max_characters' => 50,
];
foreach ($options as $option) {
$customOption = $this->customOptionFactory->create(['data' => $option]);
$customOption->setProductSku($product->getSku());
$customOptions[] = $customOption;
}
$product->setCanSaveCustomOptions(true)
->setOptions($customOptions)
->setHasOptions(true)
->save();
the custom option save successfully, now i want to delete the custom option programmatically, is there a way to do this?
2 Answers 2
To simply remove all the custom options from all products use the below one time script. Add it in any of your controller.
$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();
} else {
echo $product->getId();
}
}
echo 'DONE';
This is one time hitting script, so no need for not using Object Manager
-
Worked for me tooVivek Khandelwal– Vivek Khandelwal2018年06月13日 11:07:55 +00:00Commented Jun 13, 2018 at 11:07
-
Worked for me tooBhavesh Prajapati– Bhavesh Prajapati2020年11月30日 05:58:54 +00:00Commented Nov 30, 2020 at 5:58
<?php
namespace Test\Module\Block;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Product extends \Magento\Framework\View\Element\Template
{
protected $productRepository;
public function __construct(
\Magento\Framework\App\Action\Context $context,
ProductRepositoryInterface $productRepository
) {
parent::__construct($context);
$this->productRepository = $productRepository;
}
}
now you can delete option like,
$product = $this->productRepository->getById(1);// replace with your product Id
if($product->getOptions() != "){
foreach ($product->getOptions() as $opt){
$opt->delete();
}
$product->setHasOptions(0)->save();
}
-
why i need to setHasOptions to 0?Hunter– Hunter2017年08月23日 08:06:29 +00:00Commented Aug 23, 2017 at 8:06
-
Because you are deleting all your product option @HunterKeyur Shah– Keyur Shah2017年08月23日 08:08:14 +00:00Commented Aug 23, 2017 at 8:08