Magento – Get Orders within a Specified Date Range Collection

A quick update again! I needed to grab all orders within a specific time frame, and run a cron job each day to grab the past 7 days worth of orders that were not set to Complete. Below is how I accomplished this.

require_once ("app/Mage.php");

function getQtyOrdered($order)
	$totalQty = 0;
	foreach($order->getItemsCollection() as $item)
		$qty = $item->getQtytoInvoice();
		$totalQty = $totalQty + $qty;
	return $totalQty;

//grab orders in the past 7 days that are NOT complete.
$lastweek = date('Y-m-d', strtotime("-1 week"));
$orders = Mage::getModel('sales/order')->getCollection()
    ->addAttributeToFilter('created_at', array('from'  => $lastweek))
	->addAttributeToFilter('status', array('neq' => Mage_Sales_Model_Order::STATE_COMPLETE));

//get data from each order
foreach($orders as $order)
		$order_data[$i] = array(
			/* Order Date */		$order->getCreatedAt(),
			/* PO# Magento */		$order->getIncrementId(),
			/* Total Qty Mag */		getQtyOrdered($order),
			/* Total $ Mag */		number_format($order->getGrandTotal(),2),
			/* Bill To Name Mag */	$order->getBillingAddress()->getName(),
			/* Ship To Name Mag */	$order->getShippingAddress()->getName()
		//do manipulation, array walks or creating CSV 

Posted in Magento, Magento Enterprise, PHP
  • Zoe

    Hey man I have followed your code. But it is not working as I expected.I mean I wanna retrieve the all orders Ids of yesterday. But it is retrieving all orders Ids.

    I am using the following code.

    $yesterday = date(‘Y-m-d’, strtotime(“yesterday”));
    $orders = Mage::getModel(‘sales/order’)->getCollection()
    ->addAttributeToFilter(‘created_at’, array(‘from’ => $yesterday))
    ->addAttributeToFilter(‘status’, array(‘neq’ => Mage_Sales_Model_Order::STATE_COMPLETE));

    //get data from each order
    foreach($orders as $order)

    echo $order->getIncrementId();
    echo “”;

  • Kasmin Nicko

    Wow thanks you saved my time… 😀

  • Pingback: Magento – Set Order Status Programmatically | Fort Wayne Web Development()