How to Get Total Number of Orders Placed by a Customer in Magento 2

magento-2.1orders

I want to show the total count that how many orders are placed by a customer at "my orders" tab in magento 2 front end.

Best Answer

view/frontend/layout/customer_account.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer-account-navigation-orders-link" remove="true"/>
        <referenceBlock name="customer_account_navigation">
            <block class="Magento\Customer\Block\Account\SortLinkInterface" name="customer-account-navigation-orders-links">
                <arguments>
                    <argument name="path" xsi:type="string">sales/order/history</argument>
                    <argument name="label" xsi:type="helper" helper="Ktpl\Contentbyzone\Helper\Data::getLabel"></argument>
                    <argument name="sortOrder" xsi:type="number">230</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

and then create

Helper/Data.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Ktpl\Contentbyzone\Helper;

use Magento\Framework\App\Action\Action;

/**
 * CMS Page Helper
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 * @SuppressWarnings(PHPMD.NPathComplexity)
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Customer\Model\Session $session,
        \Magento\Sales\Model\OrderFactory $orderFactory
    ) {
        $this->_session = $session;
        $this->_orderFactory = $orderFactory;
        parent::__construct($context);
    }

    public function getLabel()
    {
        $count = count($this->getOrders());
        return "My Order(".$count.")";
    }

    public function getOrders()
    {
        $customerId = $this->_session->getCustomer()->getId();
        $this->orders = $this->_orderFactory->create()->getCollection()->addFieldToSelect(
            '*'
        )->addFieldToFilter(
            'customer_id',
            $customerId
        )->setOrder(
            'created_at',
            'desc'
        );
        return $this->orders;
    }
}

enter image description here

Related Topic