Magento is powerful enough to handle small business as well as large retail stores like Hermes, Paul Smith, Ford, Nike etc. But at behind it takes huge efforts of the store owner to maintain products and run a successful e-commerce store. And we developers are born to drink coffee and to simplify the daily routine task of store owners so they can utilize this time to focus on other factors of the store.
Recently one of our clients was asking us about a script where he wants to add products to cart programmatically to save his time and efforts. Actually, that script is pretty useful to everyone so we decided to share the script on our MageComp blog.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
protected $formKey; protected $cart; protected $product; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Data\Form\FormKey $formKey, \Magento\Checkout\Model\Cart $cart, \Magento\Catalog\Model\Product $product, array $data = []) { $this->formKey = $formKey; $this->cart = $cart; $this->product = $product; parent::__construct($context); } public function execute() { $productId =10; // Your Product Id $params = array( 'form_key' => $this->formKey->getFormKey(), 'product' => $productId, 'qty' =>1 //quantity of product ); //Load the product based on productID $_product = $this->product->load($productId); $this->cart->addProduct($_product, $params); $this->cart->save(); |
You can even use or customize this code as per your need to add more additional or custom options as well as configurable product code.
Hope you liked this tiny little solution. Don’t forget to smash that down stars and comment down below if you face any issue while implementing this code.
Happy Coding!
Useful article! Thanks and Keep sharing!
Useful article! Thanks and Keep sharing!