Using WordPress ’email_exists()’ PHP function

The email_exists() WordPress PHP function is used to determine if a given email address exists in the system.

Usage

Here’s a simple example to demonstrate how to use the email_exists() function. Let’s assume we want to check if the email ‘[email protected]’ is registered in our WordPress site.

$email = '[email protected]';
$exists = email_exists($email);

if ($exists) {
    echo "That E-mail is registered to user number " . $exists;
} else {
    echo "That E-mail doesn't belong to any registered users on this site";
}

In this example, if the email exists, the function will return the user ID associated with that email. If it doesn’t exist, the function will return false.

Parameters

  • $email (string): This is the email address that you want to check for existence.

More information

See WordPress Developer Resources: email_exists()

This function is not defined in SHORTINIT. Therefore, make sure to use it in a full WordPress environment.

Examples

Checking for a specific email

We want to check if ‘[email protected]’ is registered on the site.

$email = '[email protected]';
$exists = email_exists($email);

if ($exists) {
    echo "The email " . $email . " is registered with user ID " . $exists;
} else {
    echo "The email " . $email . " is not registered on this site";
}

Checking for a dynamically inputted email

This example shows how to check for an email that has been inputted by a user in a form.

$email = $_POST['email'];
$exists = email_exists($email);

if ($exists) {
    echo "Thank you for logging in, your user ID is " . $exists;
} else {
    echo "This email is not registered. Please sign up.";
}

Checking multiple emails in an array

Suppose we have an array of emails and we want to find out which ones are registered.

$emails = ['[email protected]', '[email protected]', '[email protected]'];
foreach ($emails as $email) {
    $exists = email_exists($email);
    if ($exists) {
        echo "The email " . $email . " is registered with user ID " . $exists;
    } else {
        echo "The email " . $email . " is not registered on this site";
    }
}

Using the function in a login process

This function can be used as part of a login process to check if the email exists before attempting a password match.

$email = $_POST['email'];
$exists = email_exists($email);

if ($exists) {
    // Proceed with password verification
} else {
    echo "This email is not registered. Please sign up.";
}

Checking for an email before registration

Before registering a new user, we can check if the email is already registered.

$email = $_POST['email'];
$exists = email_exists($email);

if ($exists) {
    echo "This email is already registered. Please log in.";
} else {
    // Proceed with registration process
}