Using WordPress ‘pre_get_sites’ PHP action

The pre_get_sites WordPress PHP action fires before sites are retrieved, allowing you to modify the WP_Site_Query instance.

Usage

add_action('pre_get_sites', 'my_custom_pre_get_sites');
function my_custom_pre_get_sites($query) {
  // your custom code here
  return $query;
}

Parameters

  • $query (WP_Site_Query): Current instance of WP_Site_Query (passed by reference).

More information

See WordPress Developer Resources: pre_get_sites

Examples

Exclude a specific site from the query

This example excludes a specific site with the ID 5 from the query.

add_action('pre_get_sites', 'exclude_specific_site');
function exclude_specific_site($query) {
  $query->query_vars['exclude'] = array(5);
  return $query;
}

Limit the number of sites retrieved

This example limits the number of retrieved sites to 3.

add_action('pre_get_sites', 'limit_site_query');
function limit_site_query($query) {
  $query->query_vars['number'] = 3;
  return $query;
}

Order sites by the last updated date

This example orders the sites by the last updated date in descending order.

add_action('pre_get_sites', 'order_sites_by_last_updated');
function order_sites_by_last_updated($query) {
  $query->query_vars['orderby'] = 'last_updated';
  $query->query_vars['order'] = 'DESC';
  return $query;
}

Filter sites by a specific language

This example filters the sites to display only those with a specific language, in this case, English.

add_action('pre_get_sites', 'filter_sites_by_language');
function filter_sites_by_language($query) {
  $query->query_vars['lang_id'] = 'en';
  return $query;
}

Filter sites by a specific domain

This example filters the sites to display only those with a specific domain, in this case, ‘example.com’.

add_action('pre_get_sites', 'filter_sites_by_domain');
function filter_sites_by_domain($query) {
  $query->query_vars['domain'] = 'example.com';
  return $query;
}