Adding products to cart with custom options or customizable options programmatically for magento 2 …

Many have had this issue or are still having when trying to do this programmatically. Especially when migrating order history before going live… ouch !

If you have scoured google looking for this, well : YOUR WELCOME 🙂 !

Here goes:


$product = $productFactory->create();
$product->setStoreId(1)->load($product->getIdBySku($sku));
$params = new \Magento\Framework\DataObject();
$params->setQty($qty);
foreach ($product->getOptions() as $o) {
foreach ($o->getValues() as $value) {
if ($value["sku"] == 'RED') { //add this if to search for your custom option by sku or the value name etc.
$options[$value['option_id']] = $value['option_type_ id'];
$params->setOptions($options); //set the customizable option to the product

}
}
}
try {
$quote1->addProduct($product, $params); //add to cart 🙂
} catch (Exception $e) {echo $e->getMessage();}