Is their any way we can get total amount that has been spend by customer in magento 2 ?
-
Total amount for all orders that have been placed by customer?– ZealousWebMar 5, 2021 at 11:14
-
yes, Total Spent on order by customer.– devhsMar 5, 2021 at 11:15
-
1I meant to ask that for particular order or all orders which have been placed by customer?– ZealousWebMar 5, 2021 at 11:17
-
Thanks for the response. All orders total placed by customer.– devhsMar 5, 2021 at 11:18
-
Thanks. Do you need it for particular customer or for all customers?– ZealousWebMar 5, 2021 at 11:19
2 Answers
You can load the order collection for example by customer email, then loop through the orders totalling the value:
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
public function __construct(
CollectionFactory $orderCollectionFactory
) {
$this->orderCollectionFactory = $orderCollectionFactory;
}
public function test()
{
$customerEmail="[email protected]";
$total=0;
$orders = $this->orderCollectionFactory->create()
->addAttributeToFilter('customer_email', $customerEmail);
foreach ($orders as $order) {
echo "Order# {$order->getIncrementId()} - Creation Date: {$order->getCreatedAt()} - Value: {$order->getGrandTotal()}". PHP_EOL;
$total=$total+$order->getGrandTotal();
}
echo "Total for customer:".$total.PHP_EOL;
}
Please add below code in any root file. Please create custom.php file in root of magento folder and check your output.
<?php
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$OrderFactory = $objectManager->create('Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$orderCollection = $OrderFactory->create()->addFieldToSelect(array('*'));
$orderCollection->addAttributeToFilter('customer_email', '[email protected]');
$total = 0;
foreach($orderCollection as $orderData)
{
$total = $total + $orderData->getGrandTotal();
}
echo $total;
die();
-
If this script is helpful for you then please approve and upvote this. Many thanks! Mar 5, 2021 at 11:40
-