How to Programmatically Add Product to Cart in Magento 2

Sometimes, Magento 2 store admin needs to prefill the shopping cart with a product whenever a user lands to the website. There are many uses of this functionality; for example, the admin may require to add a virtual product to cart whenever a particular product is added to the cart by a customer, the admin may want to give away the free product by default, the admin requires to integrate a custom system or he may require to send visitors directly to the checkout with the product in the cart.

Default Magento 2 doesn’t allow this. So, I’ve come up with a method to programmatically add product to cart in Magento 2.


Method to Programmatically Add Product to Cart in Magento 2:


Run the above code and your task is done in a blink of an eye! Please let me know in the comment section if everything worked as expected. I would be happy to help if you stuck somewhere.

If you think this code saved you time, rate the post with 5 stars ?

Thank You!

Get Weekly Updates

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

Thank you for subscribing.

Something went wrong.

(based on 26 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.

13 comments On How to Programmatically Add Product to Cart in Magento 2

Leave a reply:

Your email address will not be published.