Load customer by custom attribute in Magento
Here is an example of slightly more advanced approach of how to load customer in Magento - load customer by attribute value - be it some default attribute or a custom one. Generally the approach is as follows.
Get customer by custom attribute in Magento
<?php
// Load collection of customers with 'attribute_code' set to 'attribute_value'
$collection = Mage::getModel('customer/customer')->getCollection()
->addFieldToFilter('attribute_code', 'attribute_value')
->load();
// In order to access each customer, collection must be iterated via foreach
foreach ($collection as $customer) {
var_dump($customer->getId()); // Get customer ID
var_dump($customer->getData()); // Get all customer data
var_dump($customer->getEmail()); // Get customer email address
var_dump($customer->getFirstname()); // Get customer firstname
}
If you need to load single / first matching customer, use the following method:
<?php
// Load collection of customers with 'attribute_code' set to 'attribute_value'
$collection = Mage::getModel('customer/customer')->getCollection()
->addFieldToFilter('attribute_code', 'attribute_value');
// Set the maximum number of customers returned in collection to 1
$collection->getSelect()->limit(1);
// Retrieve the first loaded customer instance
$customer = $collection->load()->getFirstItem();
// Customer existence check and some data retrieval
if ($customer->getId()) {
var_dump($customer->getId());
var_dump($customer->getData());
var_dump($customer->getEmail());
var_dump($customer->getFirstname());
}
You can also load customers that match multiple criteria:
<?php
// Load collection of customers with 'firstname' set to 'John' and 'website_id' set to '1'
$collection = Mage::getModel('customer/customer')->getCollection()
->addFieldToFilter('firstname', 'John')
->addFieldToFilter('website_id', 1);
// Set the maximum number of customers returned in collection to 1
$collection->getSelect()->limit(1);
// Retrieve the first loaded customer instance
$customer = $collection->load()->getFirstItem();
// Customer existence check and some data retrieval
if ($customer->getId()) {
var_dump($customer->getId());
var_dump($customer->getData());
var_dump($customer->getEmail());
var_dump($customer->getFirstname());
}
If you are looking how to load customer by its ID or by email address, you can check these posts: load customer by ID in Magento and load customer by email in Magento.