I have a loop that pulls in all sites in my multisite site network and loops through them to get variables located in their ACF options. Here is an excerpt from the code I am using:

    $stageurl = array();
    $args = array(
        'public'     => true,
        'limit'      => 500
    );

    $sites = wp_get_sites($args);

    foreach ($sites as $site) {
        switch_to_blog($site['blog_id']);
        $stage = get_field('stage', 'option');
        if (isset($stage)) {
            $stageurl[] = $site['domain'];
        }
        restore_current_blog();
    }

    foreach ($stageurl as $i => $stages) {
        ...
    }

Using wp_get_sites, how are sites sorted by default?

Ideally I would like to sort sites by their creation date before adding them to my foreach loop. Is it possible to find a network site’s creation date and use it to sort my $stageurl array?

4 Answers
4

Using get_sites() in WP 4.6+

It looks like wp_get_sites() will be deprecated in WP 4.6.

The new replacement is:

function get_sites( $args = array() ) {
        $query = new WP_Site_Query();

        return $query->query( $args );
}

Very similar to get_posts() and WP_Query.

It supports various useful parameters and filters.

Here’s what the inline documentation says about the orderby input parameter:

  • Site status or array of statuses.
  • Default id
  • Accepts:

    • id
    • domain
    • path
    • network_id
    • last_updated
    • registered
    • domain_length
    • path_length
    • site__in
    • network__in
  • Also accepts the following to disable ORDER BY clause:

    • false
    • an empty array
    • none

The default of the order parameter is DESC.

Example

Here’s an example (untested) how we might try to order public sites by registration date:

$mysites = get_sites( 
    [
        'public'  => 1,
        'number'  => 500,
        'orderby' => 'registered',
        'order'   => 'DESC',
    ]
);

and returning at max 500 sites.

Update

Thanks to @fostertime for noticing that the boolean value of the public parameter. It’s not supported. It should be 1 not true in the example here above.

I therefore filed a ticket here (#37937) to support boolean strings for the public, archived, mature, spam and deleted attributes in WP_Site_Query.

Leave a Reply

Your email address will not be published. Required fields are marked *