Reading list Switch to dark mode

    Add Product in Cart Programmatically from observers, blocks, helper, plugin etc

    Updated 28 March 2024

    Add Product in Cart Programmatically from observers, blocks, helper, plugin etc.

    There are just few lines of code to add a product in cart using cart model.

    Write the following code in the function of your class of (observer, block, helper, plugin) to add product in cart.

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    
    $cart = $objectManager->get(
        'Magento\Checkout\Model\Cart'
    );
    $productRepo = $objectManager->get(
        'Magento\Catalog\Model\ProductRepository'
    );
    
    $productData = [];
    $productData['qty'] = PRODUCT_QUANTITY; // input  here for quantity of product, for. e.g : 5
    $productData['product'] = PRODUCT_ID; // input product id here, for e.g : 1
    
    $_product = $productRepo->getById(PRODUCT_ID);
    if ($_product) {
        $cart->addProduct($_product, $productData); // adds product in cart using cart model
    }
    $cart->save();
    $cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
    $cart->getQuote()->save();

    Searching for an experienced
    Magento Company ?
    Find out More
    . . .

    Leave a Comment

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


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home