How to Add Product to Cart Programmatically With Custom Options in Magento 2

Earlier, I showed you How to Add Magento 2 Configurable Products Programmatically to Cart

Now, what if you are required to add product to cart programmatically with custom options in Magento 2?

Crazy business requirements, isn’t it? 

I get you, fellow developers

Moreover, this solution can also be helpful if you want an automatic “add to cart” functionality for the configurable product with custom options. For example, the store is offering a free product with a particular product, attach a warranty, or add a gift product!

But what if such products you are adding to the Magento 2 cart are the configurable product! And, if that was not enough, they have custom options too! It can be a bit tricky. Along with custom options you can also add product to cart with custom price that allows store to create products with custom price in their online store.

Here’s the solution for the same:

Method to Add Product to Cart Programmatically With Custom Options in Magento 2:

1. Create registration.php file in app\code\[Vendor]\[Namespace]\

<?php
    MagentoFrameworkComponentComponentRegistrar::register(
			MagentoFrameworkComponentComponentRegistrar::MODULE,
			'[Vendor]_[Namespace]',
			__DIR__
		);

2. Create module.xml file in app\code\[Vendor]\[Namespace]\etc

<?xml version="1.0"?>
	<config xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance" xsi_noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
		<module name="[Vendor]_[Namespace]" setup_version="1.0.0"/>
	</config>

3. Create Data.php file in app\code\[Vendor]\[Namespace]\Helper

<?php

namespace [Vendor][namespace]Helper;

use MagentoFrameworkAppHelperAbstractHelper;
use MagentoFrameworkAppHelperContext;
use MagentoCheckoutModelCart;
use MagentoCatalogModelProductFactory;

class Data extends AbstractHelper
{
    private $cart;
    private $productFactory;
    
    public function __construct(Context $context, Cart $cart, ProductFactory $productFactory)
    {

        $this->productFactory = $productFactory;
        $this->cart = $cart;
        parent::__construct($context);

    }

    public function getAddCustomProduct($productId)
    {
        $product = $this->productFactory->load($productId);

        $cart = $this->cart;

        $params = array();
        $options = array();
        $params['qty'] = 1;
        $params['product'] = $productId;

        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();


    }
}

You can use the above helper method by passing product id in anywhere in Magento 2.

That’s it.

Thank you.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...