Load customer by custom attribute in Magento

February 01, 2016 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 default attribute or custom one. Generally, the approach is as follows.


Get customer by custom attribute in Magento

// 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:

// 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:

// 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.