Magento 2 – How to Get All Guest Orders

In this post I am going to explain how to get guest orders collection in Magento 2.

1. Using Dependency Injection

Add below code snippet in Block class.

protected $_orderCollectionFactory;
        
public function __construct(
	\Magento\Backend\Block\Template\Context $context,
	\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
	array $data = []
)
{
	$this->_orderCollectionFactory = $orderCollectionFactory;
	parent::__construct($context, $data);
}

public function getGuestOrderCollection() 
{
	$orderCollecion = $this->_orderCollectionFactory->create()
			->addFieldToSelect('*')
			->addAttributeToFilter('customer_is_guest', ['eq' => 1]);
	return $orderCollecion;
}

Add below code snippet in template file.

// Get Guest Order Collection
$guestOrderCollection = $block->getGuestOrderCollection();

echo "<pre>";
print_r($guestOrderCollection->getData());
echo "</pre>";

if ($guestOrderCollection && count($guestOrderCollection) > 0) {
    foreach ($guestOrderCollection AS $order) {
        echo $order->getId() . "<br/>";
        echo $order->getStatus() . "<br/>";
    }
}

2. Using Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$orderCollectionFactory = $objectManager->get('Magento\Sales\Model\ResourceModel\Order\CollectionFactory')->create();

// Get Guest Order Collection
$guestOrderCollection = $orderCollectionFactory->addFieldToSelect('*')
        ->addAttributeToFilter('customer_is_guest', ['eq' => 1]);

echo "<pre>";
print_r($guestOrderCollection->getData());
echo "</pre>";

if ($guestOrderCollection && count($guestOrderCollection) > 0) {
    foreach ($guestOrderCollection AS $order) {
        echo $order->getId() . "<br/>";
        echo $order->getStatus() . "<br/>";
    }
}

Thats it.

1 Comment

  1. Very good this content, great worked here. Thanks team.

Leave a Reply

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