Using WordPress ‘get_site_by_path()’ PHP function

The get_site_by_path() WordPress PHP function retrieves the closest matching site object by its domain and path.

Usage

$site = get_site_by_path( 'example.com', '/blog/' );

Parameters

  • $domain (string) – The domain to check.
  • $path (string) – The path to check.
  • $segments (int|null, optional) – The path segments to use. Defaults to null, or the full path. Default: null.

More information

See WordPress Developer Resources: get_site_by_path()

Examples

Find a site by domain and path

Get a site object for the given domain and path.

$domain = 'example.com';
$path = '/blog/';

$site = get_site_by_path( $domain, $path );

Find a site by domain and path with specific segments

Get a site object for the given domain and path, using a specific number of path segments.

$domain = 'example.com';
$path = '/blog/category/';
$segments = 2;

$site = get_site_by_path( $domain, $path, $segments );

Check if a site exists by domain and path

Verify if a site exists for the given domain and path, and output a message accordingly.

$domain = 'example.com';
$path = '/blog/';

$site = get_site_by_path( $domain, $path );

if ( $site ) {
    echo 'Site found!';
} else {
    echo 'Site not found!';
}

Display site information

Get a site object for the given domain and path, and display its information.

$domain = 'example.com';
$path = '/blog/';

$site = get_site_by_path( $domain, $path );

if ( $site ) {
    echo 'Site ID: ' . $site->id;
    echo 'Site Domain: ' . $site->domain;
    echo 'Site Path: ' . $site->path;
} else {
    echo 'Site not found!';
}

Find all sites with a specific domain

Get all sites with the same domain and display their paths.

$domain = 'example.com';
$all_sites = get_sites( array( 'domain' => $domain ) );

foreach ( $all_sites as $site ) {
    echo 'Site Path: ' . $site->path . '<br>';
}