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
<?php namespace Vendor\Extension\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Framework\Data\Form\FormKey; use Magento\Checkout\Model\Cart; use Magento\Catalog\Model\Product; class Post extends Action { protected $formKey; protected $cart; protected $product; public function __construct( Context $context, FormKey $formKey, Cart $cart, Product $product) { $this->formKey = $formKey; $this->cart = $cart; $this->product = $product; parent::__construct($context); } public function execute() { $productId =10; $params = array( 'form_key' => $this->formKey->getFormKey(), 'product' => $productId, 'qty' =>1 ); $product = $this->product->load($productId); $this->cart->addProduct($product, $params); $this->cart->save(); } }
Run the above code and your task is done in a blink of an eye!
You can also try to manually add sticky add to cart in Magento.
Thank You!