Let me give you one example.
I am creating one demo root script file for achieve our goal.
Please check below code.
$productId = 127;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$cart = $objectManager->create('Magento\Checkout\Model\Cart');
$params = array();
$options = array();
$params['qty'] = 1;
$params['product'] = 127;
foreach ($product->getOptions() as $o)
{
foreach ($o->getValues() as $value)
{
$options[$value['option_id']] = $value['option_type_id'];
}
}
$params['options'] = $options;
$cart->addProduct($product, $params);
$cart->save();
This code is work for me and it's successfully add product to cart with custom option in frontend. Note :
Please do not use object manager directly in your code. it's not recommended.
Please create object using dependency injection.
Let's discuss above code.
I have statically take one product id for add product to cart and then load that product for get product details with it's options.
I have pass the options in params array. In params we have already assigned number of qty and product id.
Create object of "Magento\Checkout\Model\Cart" and it's addProduct method use add proudct to cart.
After setting options in params, we will pass params and product object to to addProduct method and fire the cart save method.
That's it. Product is successfully added with options in cart.