🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Programmatically Add Product to Cart in Magento

By Sanjay JethvaUpdated on May 22, 2025 1 min read

Earlier, I had given the solution to programmatically add product to cart in Magento 2.

Have you ever thought to surprise your customers with some discounted or FREE stuff? Hell yeah! You may add products to cart automatically when a customer performs a specific action like store visit, reach a specific subtotal, adds a particular product to cart, etc. Also add product to cart with custom price that allows the Magento store owners to create products with custom price in their online stores.

Follow the below code to not only programmatically add product to cart in Magento, but also update the mini cart automatically.

Use this method when, as an admin, you want to offer a free product, add a virtual product or sample product. Customize the code to meet your specific requirements of adding the products to cart automatically.

Steps to Programmatically Add Product to Cart in Magento:

$prod_id = 41; // pass product id
$_product = Mage::getModel('catalog/product')->load($prod_id);
$params = array(
   'product' => $prod_id,
   'qty' => 1
);

$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product, $params);
$cart->save();

$quote = Mage::getModel('checkout/session')->getQuote();
$quote->collectTotals()->save();

That’s it.

Automate adding products to cart in Magento.

Thanks.

Sanjay Jethva Full Image
Article bySanjay 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 businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.