'How to get list of all sites in Wordpress Multisite Network?

I need some php request for get list of all sites in wp-network. Is it possible?



Solution 1:[1]

As of WP 4.6 there is a new function to query sites, get_sites($query_arg) which is a parallel to the familiar get_posts($query_args) used for retrieving posts,

$blogs = get_sites();
foreach( $blogs as $b ){
    $b->blog_id 
    //Do stuff
}  

NOTE: As pointed out by @guido-walter-pettinari in the comment below, get_sites() is a front for instantiating a new WP_Sites_query object which sets some default query parameters, including the 'number' of sites to return to 100!

Solution 2:[2]

Using WordPress functions is a bit problematic, when you aim compatibility with all multisite versions:

  • get_blog_list is not only deprecated, but it does not return sites not flagged as public either. Strangely, the oficial documentation hasn't warned us about that (you discover only when your code fails).
  • get_sites, in contrast, works only in WP 4.6.0 or higher

I prefer using the following code, which is compatible with all WordPress versions (as of 3.0.0, of course), and returns all sites of the installation (even the archived ones, deactivated ones, etc.):

global $wpdb;  
$blogs = $wpdb->get_results( "SELECT blog_id, domain, path FROM $wpdb->blogs ORDER BY blog_id" );

If you want to filter your results, not showing the archived ones, deactivated ones and spam sites, you have to indicate that in the query as follows:

global $wpdb;
$blogs = $wpdb->get_results( "SELECT blog_id, domain, path FROM $wpdb->blogs WHERE archived = '0' AND deleted = '0' AND spam = '0' ORDER BY blog_id" );

Note: $blogs array is an object collection; you will have to build your own site list with the informations that comes inside every object (id, path, domain) that is more appropriate for you, as exemplified in Firefog and Aurovrata answers.

Solution 3:[3]

In the usual way, you will be unable to get the blog name. To fetch blog names, you can use this little hack as follows.

$blog_list = get_blog_list(0, 'all');
foreach ($blog_list as $blog) {
    switch_to_blog( $blog['blog_id'] );
    $option = 'blogname';
    $value = get_option( $option );
    echo $value . '<br />';
    restore_current_blog();
}

Also, you can use the following alternative method to get the same result by calling the database directly.

global $wpdb;
foreach ($wpdb->get_results("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE archived = '0' AND deleted = '0' AND spam = '0' ORDER BY blog_id") as $key => $blog) {
    switch_to_blog( $blog->blog_id );
    $option = 'blogname';
    $value = get_option( $option );
    echo $value . '<br />';
    restore_current_blog();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Sathnindu Kottage