Using WordPress ‘domain_exists()’ PHP function

The domain_exists() WordPress PHP function checks whether a site name is already in use. It is typically used during the new site registration process to ensure that each site name is unique. The name can be a site’s subdomain or the site’s subdirectory path depending on the network settings.

Usage

$result = domain_exists( $domain, $path, $network_id );

In this example, $domain is the domain name to be checked, $path is the path to be checked, and $network_id is an optional network ID, relevant only on multi-network installations.

Parameters

  • $domain (string): The domain to be checked. It is a required parameter.
  • $path (string): The path to be checked. It is a required parameter.
  • $network_id (int): Network ID. This is an optional parameter and is only relevant on multi-network installations. The default value is 1.

More information

See WordPress Developer Resources: domain_exists()

Examples

Basic Usage

// Check if 'mywebsite.com' exists
$result = domain_exists('mywebsite.com', '/');
if ($result) {
    echo 'The domain exists.';
} else {
    echo 'The domain does not exist.';
}

In this example, we’re checking whether the domain ‘mywebsite.com’ exists. The path is set to root (‘/’).

Checking a Subdomain

// Check if subdomain 'blog.mywebsite.com' exists
$result = domain_exists('mywebsite.com', '/blog');
if ($result) {
    echo 'The subdomain exists.';
} else {
    echo 'The subdomain does not exist.';
}

Here, we’re checking for a specific subdomain (‘blog.mywebsite.com’) under ‘mywebsite.com’. The path is set to ‘/blog’.

Checking a Domain on a Specific Network

// Check if 'mywebsite.com' exists on network 2
$result = domain_exists('mywebsite.com', '/', 2);
if ($result) {
    echo 'The domain exists on network 2.';
} else {
    echo 'The domain does not exist on network 2.';
}

This example checks if ‘mywebsite.com’ exists on a specific network (network 2). The path is set to root (‘/’).

Checking a Subdirectory

// Check if 'mywebsite.com/shop' exists
$result = domain_exists('mywebsite.com', '/shop');
if ($result) {
    echo 'The subdirectory exists.';
} else {
    echo 'The subdirectory does not exist.';
}

In this example, we’re checking for a specific subdirectory (‘/shop’) under ‘mywebsite.com’.

Checking a Non-Existent Domain

// Check if 'nonexistentwebsite.com' exists
$result = domain_exists('nonexistentwebsite.com', '/');
if ($result) {
    echo 'The domain exists.';
} else {
    echo 'The domain does not exist.';
}

This example checks if a non-existent domain (‘nonexistentwebsite.com’) exists, illustrating how the function can be used to validate new domains.