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

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.

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]\
  2. Create module.xml file in app\code\[Vendor]\[Namespace]\etc
  3. Create Data.php file in app\code\[Vendor]\[Namespace]\Helper

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

That’s it.

Do let me know in the Comments section below if you have issues in the implementation of the given solution. I’d be happy to help.

Thank you.

4.3
(based on 6 Reviews)

Sanjay is a co-founder at Meetanshi. He is a certified Magento developer who loves creating Magento E-commerce solutions. When he is not engrossed with anything related to Magento, he loves to play cricket.

Leave a Reply