How To

Magento 2: How to Programmatically Add Configurable Products to Cart

Hello Magento Friends,

In today’s blog, we will learn about How to Programmatically Add Configurable Products to Cart in Magento 2.

Adding products to the cart programmatically is a common requirement when building custom functionalities in Magento 2. This is especially important when dealing with configurable products, as these require not only the main product information but also the associated child product (simple product) based on selected attributes like size, color, etc.

Magento 2: Get Simple Product from Configurable Product before Add to Cart

In this blog, we’ll guide you through the process of programmatically adding configurable products to the cart in Magento 2.

Steps to Programmatically Add Configurable Products to Cart in Magento 2:

Step 1: We need to create a “configurable_addtocart.php“ file inside the Magento root directory.

magento_root_directory\configurable_addtocart.php

Then add the code as follows

<?php
 use Magento\Framework\AppInterface;

 try {
     require_once __DIR__ . '/app/bootstrap.php';

 } catch (\Exception $e) {
     echo 'Autoload error: ' . $e->getMessage();
     exit(1);
 }
 try{
  $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
  $objectManager = $bootstrap->getObjectManager();
  $appState = $objectManager->get('\Magento\Framework\App\State');
  $appState->setAreaCode('frontend');

  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $cart = $objectManager->get('Magento\Checkout\Model\Cart');
  $productId = 10; // set Configurable Product Id
  $product = $objectManager->create('Magento\Catalog\Model\ProductFactory')->create()->load($productId);
  $_children = $product->getTypeInstance()->getUsedProducts($product);
      foreach ($_children as $child){
  $childId = $child->getID();
   $childProduct = $objectManager->create('Magento\Catalog\Model\ProductFactory')->create()->load($childId);
   $params = [];
   $params['product'] = $product->getId();
   $params['qty'] = 2;
   $options = [];
   $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
   foreach($productAttributeOptions as $option){
       $options[$option['attribute_id']] =  $childProduct->getData($option['attribute_code']);
   }
   $params['super_attribute'] = $options;
   
   /*Add product to cart */   $product = $objectManager->create('Magento\Catalog\Model\ProductFactory')->create()->load($product->getId());
   $cart->addProduct($product, $params);
   $cart->save();
      }
  echo "Product Added Successfully";
 }
 catch(\Exception $e){
  print_r($e->getMessage());
 }
?>

Conclusion:

By following the above step, you can effectively add configurable products to the cart programmatically in your Magento 2 store. If you have any doubts, let me know through the comment box. Share the tutorial with your friends and stay tuned with us for more.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

12 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

2 days ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

2 days ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

2 weeks ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago