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.

Get Weekly Updates

Never miss Magento tips, tricks, tutorials, and news.

Thank you for subscribing.

Something went wrong.

4.7
(based on 13 Reviews)

Sanjay is a co-founder at Meetanshi. He is a Certified Magento Developer who loves creating Magento E-commerce solutions. Owing to his contributions in Magento Forums and posting solutions, he is among the top 50 contributors of the Magento community in 2019. When he is not engrossed with anything related to Magento, he loves to play cricket.

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

Leave a reply:

Your email address will not be published.