Appearance
How to get Magento customer ID
Note: The following examples use Magento 1 syntax. Magento 1 reached end-of-life in June 2020. For modern implementations, see the Magento 2 alternatives below.
Example of getting the customer ID of a logged-in customer in Magento 1
php
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customerId = $customer->getId();This code first gets the customer session, and then calls the getCustomer method to get the customer object. The getId method is then called on the customer object to get the customer's ID.
If you want to get the customer ID by email, you can use the following code:
Example of getting the customer ID by email in Magento 1
php
$customer = Mage::getModel('customer/customer')->loadByEmail($email);
if ($customer->getId()) {
$customerId = $customer->getId();
}This code loads the customer object by passing the email to the loadByEmail method, and then calls the getId method to get the customer's ID. Note that loadByEmail returns a model with ID 0 if the email is not found, so a safety check is recommended.
Magento 2 Alternative
In Magento 2, use the CustomerRepositoryInterface via dependency injection:
php
// Inject CustomerRepositoryInterface via the constructor
$customer = $this->customerRepository->get($email);
$customerId = $customer->getId();This approach follows Magento 2 best practices, avoids legacy static calls, and properly handles customer data retrieval.