Magento 2 Add Product To Cart Programmatically.

Hello Guys! 👋

In this blog, we add simple products to the cart using Magento 2 root scripts.

first, you need to add the following file to your Magento 2 root directory.

Step 1: add add-to-cart.php file in your magento 2 root.
<?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');
 
    $formKey = $objectManager->get('Magento\Framework\Data\Form\FormKey');
    $cart = $objectManager->get('Magento\Checkout\Model\Cart');
    $product = $objectManager->get('Magento\Catalog\Model\Product');

    $productId = 3;
    $params = array(
        'form_key' => $formKey->getFormKey(),
        'product' => $productId, //product Id
        'qty'   =>1 //quantity of product
    );
    //Load the product based on productID
    $_product = $product->load($productId);
    $cart->addProduct($_product, $params);
    $cart->save();
}
catch(\Exception $e){
    print_r($e->getMessage());
}




Step 2: Now run add-to-cart.php from Browser

Hope! It will help you

Thank you 😊

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 13

No votes so far! Be the first to rate this post.

7 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *