Magento: Add / Delete / View Custom Options of Product Programmatically
Custom options on Magento products are designed to make simple products function like a configurable product with different choosing options like color, size, etc. before purchasing the product. In this tutorial, I present the code to create/add, view, and delete custom options of a product in Magento. ADD CUSTOM OPTIONS In the following example code, I am adding custom option with title ‘Color’ and I have added two values to it ‘Red’ and ‘Gold’.
DISPLAY CUSTOM OPTIONS OF A PRODUCT
DELETE CUSTOM OPTIONS OF A PRODUCT
Hope it helps. Thanks.
<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$productId = YOUR_PRODUCT_ID;
$product = Mage::getModel('catalog/product')->load($productId);
$options = array(
'title' => 'Color',
'type' => 'drop_down',
'is_required' => 1,
'sort_order' => 0,
'values' => array(
array(
'title' => 'Red',
'price' => 10.50,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => 0,
),
array(
'title' => 'Gold',
'price' => 0,
'price_type' => 'percent',
'sku' => 'test-product-sku',
'sort_order' => 0,
)
)
);
$product->setProductOptions(array($options));
$product->setCanSaveCustomOptions(true);
$product->save();
?>
DISPLAY CUSTOM OPTIONS OF A PRODUCT
<?php
$productId = YOUR_PRODUCT_ID;
$product = Mage::getModel('catalog/product')->load($productId);
$customOptions = $product->getOptions();
foreach ($customOptions as $option) {
//print_r($option->getData());
echo "<div style='background-color: #eeeeee; border: 1px solid #666666; margin-bottom: 5px; padding: 5px'>";
echo "<strong>Option</strong><br />";
echo "ID: " . $option->getOptionId() . '<br />';
echo "Title: " . $option->getTitle() . '<br />';
echo "Type: " . $option->getType() . '<br />';
echo "Is Required: " . $option->getIsRequired() . '<br />';
echo "Sort Order: " . $option->getSortOrder() . '<br />';
echo "<br />";
echo "<strong>Values</strong><br />";
$values = $option->getValues();
foreach($values as $value) {
//print_r($value->getData());
echo "Value ID: " . $value->getOptionTypeId() . '<br />';
echo "Option ID: " . $value->getOptionId() . '<br />';
echo "Title: " . $value->getTitle() . '<br />';
echo "Price: " . $value->getPrice() . '<br />';
echo "Price Type: " . $value->getPriceType() . '<br />';
echo "SKU: " . $option->getSku() . '<br />';
echo "Sort Order: " . $option->getSortOrder() . '<br />';
echo "<br />";
}
echo "</div>";
}
?>
DELETE CUSTOM OPTIONS OF A PRODUCT
<?php
$productId = YOUR_PRODUCT_ID;
$product = Mage::getModel('catalog/product')->load($productId);
$customOptions = $product->getOptions();
foreach ($customOptions as $option) {
$option->delete();
}
$product->setHasOptions(0);
$product->save();
?>
Hope it helps. Thanks.
Pritesh
Pritesh Pethani