This problem first came into awareness as the order histories page (*/sales/order/history/) in frontend was displaying nothing but a short message: You have placed no orders.
After some debugging, it turns out the problem lies with this function:
Mage::getSingleton('customer/session')
It does not return a session entity containing current customer's information except the website id, which is why the order collection returns an empty result after filtering on the customer id.
There is actually a post on Stack Overflow discussing a similar problem: Customer session is different in different parts of a Magento website . But it has not given a good explaination.
And what is confusing is that, with my case, the function works well in some parts but not the others. For example, I inserted
<?php echo var_export(Mage::getSingleton('customer/session')->getCustomerId(), true) ?>
into the catalog product list template, and it displays the customer id after login. But the same line returns Null in the order histories page.
I located these codes in app/code/core/Mage/Customer/Model/Session.php
public function getCustomer()
{
...
$customer = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
if ($this->getId()) {
$customer->load($this->getId());
}
$this->setCustomer($customer);
return $this->_customer;
}
After setting the website id, it loads the customer entity depending on $this->getId().
Why the 'id' attribute of customer session entity is not always valid? Can someone share his knowledge please. Many thanks.