WordPress documentation is usually robust. However, recently I had a use case where I needed to query sites by custom meta values.

In WordPress 5.1, the WP_Site_Query was introduced to allow a faster way to query sites in a WordPress Multisite setup without using the old hack of needing to get all ID values using get_sites and then inside of a loop using switch_to_blog to query the sites and get values.

You can find documentation for individual meta query functions like get_site_meta but very little documentation on the WP_Site_Query class. At best, you'll come across this Make post from 2019.

Meta values on sites allow you to categorise them and have configuration values unique to that site. In my use case, I need to be able to group sites by country. If I wanted to say, "Query all sites that are for Australia" I need a list of sites that match the meta_key country value of Aurelia.

We already know you can query posts and taxonomies using meta_query and tax_query — but you can also query sites using meta queries for sites as well. It turns out, if you dig into the source code for the WP_Site_Query class, it supports a lot more than the light documentation suggests.

        // WP_Site_Query arguments         $args = array(             'meta_query' => array(                 array(                     'key'   => 'country',                     'value' => 'australia'                 )             )         );          // The Site Query         $site_query = new WP_Site_Query( $args );

Now, assuming that our site has a meta key of country and we find one or more sites with Australia as the value, we'll get back a list of sites.

Like you can with WP_Query, you can also have multiple meta queries, relationships and other useful query vars to query your sites. The only limitation is the metadata that you have.