3 * Site API: WP_Site_Query class
11 * Core class used for querying sites.
15 * @see WP_Site_Query::__construct() for accepted arguments.
20 * SQL for database query.
35 protected $sql_clauses = array(
45 * Date query container.
49 * @var object WP_Date_Query
51 public $date_query = false;
54 * Query vars set by the user.
63 * Default values for query vars.
69 public $query_var_defaults;
72 * List of sites located by the query.
81 * The amount of found sites for the current query.
87 public $found_sites = 0;
90 * The number of pages.
96 public $max_num_pages = 0;
99 * Sets up the site query, based on the query vars passed.
104 * @param string|array $query {
105 * Optional. Array or query string of site query parameters. Default empty.
107 * @type array $site__in Array of site IDs to include. Default empty.
108 * @type array $site__not_in Array of site IDs to exclude. Default empty.
109 * @type bool $count Whether to return a site count (true) or array of site objects.
111 * @type array $date_query Date query clauses to limit sites by. See WP_Date_Query.
113 * @type string $fields Site fields to return. Accepts 'ids' (returns an array of site IDs)
114 * or empty (returns an array of complete site objects). Default empty.
115 * @type int $ID A site ID to only return that site. Default empty.
116 * @type int $number Maximum number of sites to retrieve. Default 100.
117 * @type int $offset Number of sites to offset the query. Used to build LIMIT clause.
119 * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
120 * @type string|array $orderby Site status or array of statuses. Accepts 'id', 'domain', 'path',
121 * 'network_id', 'last_updated', 'registered', 'domain_length',
122 * 'path_length', 'site__in' and 'network__in'. Also accepts false,
123 * an empty array, or 'none' to disable `ORDER BY` clause.
125 * @type string $order How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'.
126 * @type int $network_id Limit results to those affiliated with a given network ID. If 0,
127 * include all networks. Default 0.
128 * @type array $network__in Array of network IDs to include affiliated sites for. Default empty.
129 * @type array $network__not_in Array of network IDs to exclude affiliated sites for. Default empty.
130 * @type string $domain Limit results to those affiliated with a given domain. Default empty.
131 * @type array $domain__in Array of domains to include affiliated sites for. Default empty.
132 * @type array $domain__not_in Array of domains to exclude affiliated sites for. Default empty.
133 * @type string $path Limit results to those affiliated with a given path. Default empty.
134 * @type array $path__in Array of paths to include affiliated sites for. Default empty.
135 * @type array $path__not_in Array of paths to exclude affiliated sites for. Default empty.
136 * @type int $public Limit results to public sites. Accepts '1' or '0'. Default empty.
137 * @type int $archived Limit results to archived sites. Accepts '1' or '0'. Default empty.
138 * @type int $mature Limit results to mature sites. Accepts '1' or '0'. Default empty.
139 * @type int $spam Limit results to spam sites. Accepts '1' or '0'. Default empty.
140 * @type int $deleted Limit results to deleted sites. Accepts '1' or '0'. Default empty.
141 * @type string $search Search term(s) to retrieve matching sites for. Default empty.
142 * @type array $search_columns Array of column names to be searched. Accepts 'domain' and 'path'.
143 * Default empty array.
144 * @type bool $update_site_cache Whether to prime the cache for found sites. Default false.
147 public function __construct( $query = '' ) {
148 $this->query_var_defaults = array(
152 'site__not_in' => '',
155 'no_found_rows' => true,
160 'network__not_in' => '',
163 'domain__not_in' => '',
166 'path__not_in' => '',
173 'search_columns' => array(),
175 'date_query' => null, // See WP_Date_Query
176 'update_site_cache' => true,
179 if ( ! empty( $query ) ) {
180 $this->query( $query );
185 * Parses arguments passed to the site query with default query parameters.
190 * @see WP_Site_Query::__construct()
192 * @param string|array $query Array or string of WP_Site_Query arguments. See WP_Site_Query::__construct().
194 public function parse_query( $query = '' ) {
195 if ( empty( $query ) ) {
196 $query = $this->query_vars;
199 $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
202 * Fires after the site query vars have been parsed.
206 * @param WP_Site_Query &$this The WP_Site_Query instance (passed by reference).
208 do_action_ref_array( 'parse_site_query', array( &$this ) );
212 * Sets up the WordPress query for retrieving sites.
217 * @param string|array $query Array or URL query string of parameters.
218 * @return array|int List of sites, or number of sites when 'count' is passed as a query var.
220 public function query( $query ) {
221 $this->query_vars = wp_parse_args( $query );
223 return $this->get_sites();
227 * Retrieves a list of sites matching the query vars.
232 * @return array|int List of sites, or number of sites when 'count' is passed as a query var.
234 public function get_sites() {
235 $this->parse_query();
238 * Fires before sites are retrieved.
242 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
244 do_action_ref_array( 'pre_get_sites', array( &$this ) );
246 // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
247 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
248 $last_changed = wp_cache_get_last_changed( 'sites' );
250 $cache_key = "get_sites:$key:$last_changed";
251 $cache_value = wp_cache_get( $cache_key, 'sites' );
253 if ( false === $cache_value ) {
254 $site_ids = $this->get_site_ids();
256 $this->set_found_sites();
259 $cache_value = array(
260 'site_ids' => $site_ids,
261 'found_sites' => $this->found_sites,
263 wp_cache_add( $cache_key, $cache_value, 'sites' );
265 $site_ids = $cache_value['site_ids'];
266 $this->found_sites = $cache_value['found_sites'];
269 if ( $this->found_sites && $this->query_vars['number'] ) {
270 $this->max_num_pages = ceil( $this->found_sites / $this->query_vars['number'] );
273 // If querying for a count only, there's nothing more to do.
274 if ( $this->query_vars['count'] ) {
275 // $site_ids is actually a count in this case.
276 return intval( $site_ids );
279 $site_ids = array_map( 'intval', $site_ids );
281 if ( 'ids' == $this->query_vars['fields'] ) {
282 $this->sites = $site_ids;
287 // Prime site network caches.
288 if ( $this->query_vars['update_site_cache'] ) {
289 _prime_site_caches( $site_ids );
292 // Fetch full site objects from the primed cache.
294 foreach ( $site_ids as $site_id ) {
295 if ( $_site = get_site( $site_id ) ) {
301 * Filters the site query results.
305 * @param array $results An array of sites.
306 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
308 $_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) );
310 // Convert to WP_Site instances.
311 $this->sites = array_map( 'get_site', $_sites );
317 * Used internally to get a list of site IDs matching the query vars.
322 * @global wpdb $wpdb WordPress database abstraction object.
324 * @return int|array A single count of site IDs if a count query. An array of site IDs if a full query.
326 protected function get_site_ids() {
329 $order = $this->parse_order( $this->query_vars['order'] );
331 // Disable ORDER BY with 'none', an empty array, or boolean false.
332 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
334 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
335 $ordersby = is_array( $this->query_vars['orderby'] ) ?
336 $this->query_vars['orderby'] :
337 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
339 $orderby_array = array();
340 foreach ( $ordersby as $_key => $_value ) {
345 if ( is_int( $_key ) ) {
353 $parsed = $this->parse_orderby( $_orderby );
359 if ( 'site__in' === $_orderby || 'network__in' === $_orderby ) {
360 $orderby_array[] = $parsed;
364 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
367 $orderby = implode( ', ', $orderby_array );
369 $orderby = "blog_id $order";
372 $number = absint( $this->query_vars['number'] );
373 $offset = absint( $this->query_vars['offset'] );
375 if ( ! empty( $number ) ) {
377 $limits = 'LIMIT ' . $offset . ',' . $number;
379 $limits = 'LIMIT ' . $number;
383 if ( $this->query_vars['count'] ) {
384 $fields = 'COUNT(*)';
389 // Parse site IDs for an IN clause.
390 $site_id = absint( $this->query_vars['ID'] );
391 if ( ! empty( $site_id ) ) {
392 $this->sql_clauses['where']['ID'] = $wpdb->prepare( 'blog_id = %d', $site_id );
395 // Parse site IDs for an IN clause.
396 if ( ! empty( $this->query_vars['site__in'] ) ) {
397 $this->sql_clauses['where']['site__in'] = "blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
400 // Parse site IDs for a NOT IN clause.
401 if ( ! empty( $this->query_vars['site__not_in'] ) ) {
402 $this->sql_clauses['where']['site__not_in'] = "blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
405 $network_id = absint( $this->query_vars['network_id'] );
407 if ( ! empty( $network_id ) ) {
408 $this->sql_clauses['where']['network_id'] = $wpdb->prepare( 'site_id = %d', $network_id );
411 // Parse site network IDs for an IN clause.
412 if ( ! empty( $this->query_vars['network__in'] ) ) {
413 $this->sql_clauses['where']['network__in'] = 'site_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )';
416 // Parse site network IDs for a NOT IN clause.
417 if ( ! empty( $this->query_vars['network__not_in'] ) ) {
418 $this->sql_clauses['where']['network__not_in'] = 'site_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )';
421 if ( ! empty( $this->query_vars['domain'] ) ) {
422 $this->sql_clauses['where']['domain'] = $wpdb->prepare( 'domain = %s', $this->query_vars['domain'] );
425 // Parse site domain for an IN clause.
426 if ( is_array( $this->query_vars['domain__in'] ) ) {
427 $this->sql_clauses['where']['domain__in'] = "domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )";
430 // Parse site domain for a NOT IN clause.
431 if ( is_array( $this->query_vars['domain__not_in'] ) ) {
432 $this->sql_clauses['where']['domain__not_in'] = "domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )";
435 if ( ! empty( $this->query_vars['path'] ) ) {
436 $this->sql_clauses['where']['path'] = $wpdb->prepare( 'path = %s', $this->query_vars['path'] );
439 // Parse site path for an IN clause.
440 if ( is_array( $this->query_vars['path__in'] ) ) {
441 $this->sql_clauses['where']['path__in'] = "path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )";
444 // Parse site path for a NOT IN clause.
445 if ( is_array( $this->query_vars['path__not_in'] ) ) {
446 $this->sql_clauses['where']['path__not_in'] = "path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )";
449 if ( is_numeric( $this->query_vars['archived'] ) ) {
450 $archived = absint( $this->query_vars['archived'] );
451 $this->sql_clauses['where']['archived'] = $wpdb->prepare( "archived = %d ", $archived );
454 if ( is_numeric( $this->query_vars['mature'] ) ) {
455 $mature = absint( $this->query_vars['mature'] );
456 $this->sql_clauses['where']['mature'] = $wpdb->prepare( "mature = %d ", $mature );
459 if ( is_numeric( $this->query_vars['spam'] ) ) {
460 $spam = absint( $this->query_vars['spam'] );
461 $this->sql_clauses['where']['spam'] = $wpdb->prepare( "spam = %d ", $spam );
464 if ( is_numeric( $this->query_vars['deleted'] ) ) {
465 $deleted = absint( $this->query_vars['deleted'] );
466 $this->sql_clauses['where']['deleted'] = $wpdb->prepare( "deleted = %d ", $deleted );
469 if ( is_numeric( $this->query_vars['public'] ) ) {
470 $public = absint( $this->query_vars['public'] );
471 $this->sql_clauses['where']['public'] = $wpdb->prepare( "public = %d ", $public );
474 // Falsey search strings are ignored.
475 if ( strlen( $this->query_vars['search'] ) ) {
476 $search_columns = array();
478 if ( $this->query_vars['search_columns'] ) {
479 $search_columns = array_intersect( $this->query_vars['search_columns'], array( 'domain', 'path' ) );
482 if ( ! $search_columns ) {
483 $search_columns = array( 'domain', 'path' );
487 * Filters the columns to search in a WP_Site_Query search.
489 * The default columns include 'domain' and 'path.
493 * @param array $search_columns Array of column names to be searched.
494 * @param string $search Text being searched.
495 * @param WP_Site_Query $this The current WP_Site_Query instance.
497 $search_columns = apply_filters( 'site_search_columns', $search_columns, $this->query_vars['search'], $this );
499 $this->sql_clauses['where']['search'] = $this->get_search_sql( $this->query_vars['search'], $search_columns );
502 $date_query = $this->query_vars['date_query'];
503 if ( ! empty( $date_query ) && is_array( $date_query ) ) {
504 $this->date_query = new WP_Date_Query( $date_query, 'registered' );
505 $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
510 $where = implode( ' AND ', $this->sql_clauses['where'] );
512 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
515 * Filters the site query clauses.
519 * @param array $pieces A compacted array of site query clauses.
520 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
522 $clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) );
524 $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
525 $join = isset( $clauses['join'] ) ? $clauses['join'] : '';
526 $where = isset( $clauses['where'] ) ? $clauses['where'] : '';
527 $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
528 $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
529 $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
532 $where = 'WHERE ' . $where;
536 $groupby = 'GROUP BY ' . $groupby;
540 $orderby = "ORDER BY $orderby";
544 if ( ! $this->query_vars['no_found_rows'] ) {
545 $found_rows = 'SQL_CALC_FOUND_ROWS';
548 $this->sql_clauses['select'] = "SELECT $found_rows $fields";
549 $this->sql_clauses['from'] = "FROM $wpdb->blogs $join";
550 $this->sql_clauses['groupby'] = $groupby;
551 $this->sql_clauses['orderby'] = $orderby;
552 $this->sql_clauses['limits'] = $limits;
554 $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
556 if ( $this->query_vars['count'] ) {
557 return intval( $wpdb->get_var( $this->request ) );
560 $site_ids = $wpdb->get_col( $this->request );
562 return array_map( 'intval', $site_ids );
566 * Populates found_sites and max_num_pages properties for the current query
567 * if the limit clause was used.
572 * @global wpdb $wpdb WordPress database abstraction object.
574 private function set_found_sites() {
577 if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
579 * Filters the query used to retrieve found site count.
583 * @param string $found_sites_query SQL query. Default 'SELECT FOUND_ROWS()'.
584 * @param WP_Site_Query $site_query The `WP_Site_Query` instance.
586 $found_sites_query = apply_filters( 'found_sites_query', 'SELECT FOUND_ROWS()', $this );
588 $this->found_sites = (int) $wpdb->get_var( $found_sites_query );
593 * Used internally to generate an SQL string for searching across multiple columns.
598 * @global wpdb $wpdb WordPress database abstraction object.
600 * @param string $string Search string.
601 * @param array $columns Columns to search.
602 * @return string Search SQL.
604 protected function get_search_sql( $string, $columns ) {
607 if ( false !== strpos( $string, '*' ) ) {
608 $like = '%' . implode( '%', array_map( array( $wpdb, 'esc_like' ), explode( '*', $string ) ) ) . '%';
610 $like = '%' . $wpdb->esc_like( $string ) . '%';
614 foreach ( $columns as $column ) {
615 $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
618 return '(' . implode( ' OR ', $searches ) . ')';
622 * Parses and sanitizes 'orderby' keys passed to the site query.
627 * @global wpdb $wpdb WordPress database abstraction object.
629 * @param string $orderby Alias for the field to order by.
630 * @return string|false Value to used in the ORDER clause. False otherwise.
632 protected function parse_orderby( $orderby ) {
637 switch ( $orderby ) {
639 $site__in = implode( ',', array_map( 'absint', $this->query_vars['site__in'] ) );
640 $parsed = "FIELD( {$wpdb->blogs}.blog_id, $site__in )";
643 $network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
644 $parsed = "FIELD( {$wpdb->blogs}.site_id, $network__in )";
655 case 'domain_length':
656 $parsed = 'CHAR_LENGTH(domain)';
659 $parsed = 'CHAR_LENGTH(path)';
670 * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary.
675 * @param string $order The 'order' query variable.
676 * @return string The sanitized 'order' query variable.
678 protected function parse_order( $order ) {
679 if ( ! is_string( $order ) || empty( $order ) ) {
683 if ( 'ASC' === strtoupper( $order ) ) {