add_product_to_cart_programmatically_magento_2 add_product_to_cart_programmatically_magento_2

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

In this code snippet, we will see how we can add a product to cart along with custom options. For that, we will create one controller file, In that file, we will define execute method. In this method using cart model, we will add a product to cart.

Create Controller

In your custom module create a controller file Post.php under app/code/Codextblog/Customcart/Controller/Index directory

namespace CodextblogCustomcartControllerIndex;
 
use MagentoFrameworkAppActionContext;

use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestInterface;
 
class Post extends MagentoFrameworkAppActionAction
{
    protected $_resultPageFactory;
    protected $_cart;
    protected $_productRepositoryInterface;
    protected $_url;
    protected $_responseFactory;
    protected $_logger;


    public function __construct(
        Context $context,
        MagentoFrameworkViewResultPageFactory $resultPageFactory,
        MagentoCheckoutModelCart $cart,
        MagentoCatalogApiProductRepositoryInterface $productRepositoryInterface,
        MagentoFrameworkAppResponseFactory $responseFactory,
        PsrLogLoggerInterface $logger
        )
    {
        $this->_resultPageFactory = $resultPageFactory;
        $this->_cart = $cart;
        $this->_productRepositoryInterface = $productRepositoryInterface;
        $this->_responseFactory = $responseFactory;
        $this->_url = $context->getUrl();
        $this->_logger = $logger;
        parent::__construct($context);
    }

    public function execute()
    {
       $productid = 111;
       
        $_product = $this->_productRepositoryInterface->getById($productid);
        $options = $_product->getOptions();

        $customoptions = array();
        $customoptions['my_custom_option'] = 'demo';

        $params = array (
            'product' => $_product->getId(),
            'qty' => 1,
            'price' => $_product->getPrice(),
            'options' => $customoptions
        );

       $this->_cart->addProduct($_product, $params);
       $this->_cart->save();

       $this->_redirect('checkout/cart/index'); 
    }

}

Update Minicart

In Magento 2 mini cart is update using knockout js. While adding a product to cart programmatically we need to specify the controller action in sections.xml file so that Magento 2 update the mini cart as well.

create sections.xml file under app/code/Codextblog/Customcart/etc/frontend directory

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="customcart/index/post">
        <section name="cart"/>
    </action>
</config>

That’s it. Using above code we can easily add product to cart programmatically.

Written by

Chirag

Chirag is a Founder & eCommerce Technology Leader at MageArmy. He leads the eCommerce development team and drives the company’s technology vision, helping businesses build, scale, and optimize high-performing online stores. With years of experience in eCommerce development, he has worked with businesses across industries to solve complex technical challenges and create scalable digital commerce solutions. He loves sharing practical insights about eCommerce development, Magento, Adobe Commerce, and the latest trends in digital commerce to help online businesses grow and succeed.