In this post, we will learn how to add additional custom options to the Magento 2 cart, you can follow these steps for the same:

  1. Create a custom module: To create a custom module, you need to create a new directory in the app/code directory and create the required files for your module.
  2. Add a custom option to the product: In Magento 2, custom options can be added to products in the backend. To add a custom option to a product, go to the backend, navigate to the product details page, and select the Custom Options tab. From there, you can add custom options to the product.
  3. Add a new option to the cart: To add the custom option to the cart, you need to extend the Magento\Checkout\Model\Cart class and add the custom option to the addProduct method.

Here’s an example of how you can extend the Magento\Checkout\Model\Cart class and add a custom option to the cart:


<?php
namespace Vendor\Module\Model;

use Magento\Checkout\Model\Cart as CheckoutCart;

class Cart extends CheckoutCart
{
    public function addProduct($productInfo, $requestInfo = null)
    {
        // Add your custom option logic here
        $requestInfo['custom_option'] = 'custom_value';
        return parent::addProduct($productInfo, $requestInfo);
    }
}
    1. Update the di.xml file: You need to update the di.xml file to replace the original Magento\Checkout\Model\Cart class with your custom class.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsi">
<preference for="Magento\Checkout\Model\Cart" type="Vendor\Module\Model\Cart"/>
</config>
  1. Flush Magento cache: Finally, flush the Magento cache by running the following command in the terminal: php bin/magento cache:flush.