How to Get the data of shopping cart items, subtotal, grand total, billing & shipping address in Magento 2
Vinh Jacker | 12-18-2024
When running your store on Magento 2 platform, it is possible to get the data of shopping cart items, subtotal, grand total, billing & shipping address. This guide will be applied to many feature development processes that relate to cart information such as sharing cart or saving cart. Hence, in this article, we will show you the way to get the data by using the commands.
Overview of retrieving the data of shopping cart items, subtotal, grand total, billing & shipping address in Magento 2
You can get information of the cart items on a whole or individually such as subtotal, grand total and billing & shipping address. Here are four approaches:
- Get all needed information in your cart.
- Get the number of items in cart and total quantity in cart.
- Get base total price and grand total price of items in cart.
- Get chosen billing and shipping addresses.
Get all needed information in your cart.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
// get quote items collection
$itemsCollection = $cart->getQuote()->getItemsCollection();
// get array of all items what can be display directly
$itemsVisible = $cart->getQuote()->getAllVisibleItems();
// get quote items array
$items = $cart->getQuote()->getAllItems();
foreach($items as $item) {
echo 'ID: '.$item->getProductId().'<br />';
echo 'Name: '.$item->getName().'<br />';
echo 'Sku: '.$item->getSku().'<br />';
echo 'Quantity: '.$item->getQty().'<br />';
echo 'Price: '.$item->getPrice().'<br />';
echo "<br />";
}
Get the number of items in cart and total quantity in cart.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$totalItems = $cart->getQuote()->getItemsCount();
$totalQuantity = $cart->getQuote()->getItemsQty();
Get base total price and grand total price of items in cart.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$subTotal = $cart->getQuote()->getSubtotal();
$grandTotal = $cart->getQuote()->getGrandTotal();
Get chosen billing and shipping addresses.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$billingAddress = $cart->getQuote()->getBillingAddress();
echo '<pre>'; print_r($billingAddress->getData()); echo '</pre>';
$shippingAddress = $cart->getQuote()->getShippingAddress();
echo '<pre>'; print_r($shippingAddress->getData()); echo '</pre>';
That is all things you will use to retrieve the data of shopping cart items, subtotal, grand total, billing & shipping address in Magento 2. Thanks for your reading and please comment below if there is any trouble.