WordPress Multisite get_sites(): Network-Wide Post Queries and switch_to_blog Patterns

Multisite: query all sites with get_sites() and switch_to_blog()

In a Multisite network every site has its own posts, options and users’ roles, in its own set of tables. Code that runs on one site sees only that site’s data. To build something across the network, a list of the latest posts of all sites or a report for the network admin, you list the sites with get_sites() and switch into each one with switch_to_blog().

Problem: The network’s main site needs a “latest from all our sites” block with the newest posts of 30 sites.

Solution: Get the public, active sites with get_sites(), call switch_to_blog() for each, query its posts, collect the data you need, call restore_current_blog(), and cache the combined result in a network transient.

Collecting posts from every site

<?php
function ha_network_latest_posts( $per_site = 3 ) {
    $cached = get_site_transient( 'ha_network_latest_' . $per_site );
    if ( false !== $cached ) {
        return $cached;
    }

    $items = array();
    $sites = get_sites( array(
        'number'   => 100,
        'public'   => 1,
        'archived' => 0,
        'spam'     => 0,
        'deleted'  => 0,
        'fields'   => 'ids',
    ) );

    foreach ( $sites as $site_id ) {
        switch_to_blog( $site_id );

        $posts = get_posts( array(
            'posts_per_page'         => $per_site,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        foreach ( $posts as $post ) {
            $items[] = array(
                'site'  => get_bloginfo( 'name' ),
                'title' => get_the_title( $post ),
                'url'   => get_permalink( $post ),
                'date'  => $post->post_date_gmt,
            );
        }

        restore_current_blog();
    }

    usort( $items, function ( $a, $b ) {
        return strcmp( $b['date'], $a['date'] );
    } );

    set_site_transient( 'ha_network_latest_' . $per_site, $items, HOUR_IN_SECONDS );

    return $items;
}

Everything that depends on the site (the permalink, the site name, the date format) is read while switched. The dates are compared in GMT because the sites may have different time zones.

What switching does and does not do

switch_to_blog() changes the table prefix of $wpdb, the object cache context and the current site ID. It does not load the other site’s plugins or theme. A custom post type, a taxonomy or a filter that exists only on the other site is unknown while you are switched; get_posts() for that post type returns nothing, and permalinks of such posts may be wrong.

Every switch costs queries and memory, so cache the result as above and keep the number of sites per request reasonable. For hundreds of sites, collect the data in a cron job, site by site, instead of on a page view.

Network options and transients

<?php
get_site_option( 'ha_network_setting', 'default' );  // stored once for the whole network
update_site_option( 'ha_network_setting', 'value' );
set_site_transient( 'ha_key', $data, HOUR_IN_SECONDS );

The site_ functions use the network’s meta table, shared by all sites; get_option() and get_transient() always work on the current site.

Creating a site and adding users

<?php
$site_id = wp_insert_site( [
    'domain'  => 'shop.example.com',   // subdomain network; for subdirectories: the network domain
    'path'    => '/',                  // and a path such as '/shop/'
    'title'   => 'Shop',
    'user_id' => get_current_user_id(), // becomes the site administrator
] );

if ( is_wp_error( $site_id ) ) {
    error_log( $site_id->get_error_message() );
} else {
    add_user_to_blog( $site_id, 42, 'editor' );
}

wp_insert_site() (WordPress 5.1+) creates the tables of the new site and fires wp_initialize_site, where plugins set up their data. Run it from code that only super admins can reach; add_user_to_blog() gives an existing network user a role on one site.

NOTE: Every switch_to_blog() must be followed by restore_current_blog(), also when an exception or an early return happens inside the loop; otherwise the rest of the request runs with the wrong site’s tables. In code that can fail, wrap the work in try { ... } finally { restore_current_blog(); }.