wp/wp-includes/class-wp-site-query.php
changeset 9 177826044cd9
parent 7 cf61fcea0001
child 16 a86126ab1dd4
--- a/wp/wp-includes/class-wp-site-query.php	Mon Oct 14 18:06:33 2019 +0200
+++ b/wp/wp-includes/class-wp-site-query.php	Mon Oct 14 18:28:13 2019 +0200
@@ -40,6 +40,22 @@
 	);
 
 	/**
+	 * Metadata query container.
+	 *
+	 * @since 5.1.0
+	 * @var WP_Meta_Query
+	 */
+	public $meta_query = false;
+
+	/**
+	 * Metadata query clauses.
+	 *
+	 * @since 5.1.0
+	 * @var array
+	 */
+	protected $meta_query_clauses;
+
+	/**
 	 * Date query container.
 	 *
 	 * @since 4.6.0
@@ -92,86 +108,104 @@
 	 *
 	 * @since 4.6.0
 	 * @since 4.8.0 Introduced the 'lang_id', 'lang__in', and 'lang__not_in' parameters.
+	 * @since 5.1.0 Introduced the 'update_site_meta_cache', 'meta_query', 'meta_key',
+	 *              'meta_value', 'meta_type' and 'meta_compare' parameters.
 	 *
 	 * @param string|array $query {
 	 *     Optional. Array or query string of site query parameters. Default empty.
 	 *
-	 *     @type array        $site__in          Array of site IDs to include. Default empty.
-	 *     @type array        $site__not_in      Array of site IDs to exclude. Default empty.
-	 *     @type bool         $count             Whether to return a site count (true) or array of site objects.
-	 *                                           Default false.
-	 *     @type array        $date_query        Date query clauses to limit sites by. See WP_Date_Query.
-	 *                                           Default null.
-	 *     @type string       $fields            Site fields to return. Accepts 'ids' (returns an array of site IDs)
-	 *                                           or empty (returns an array of complete site objects). Default empty.
-	 *     @type int          $ID                A site ID to only return that site. Default empty.
-	 *     @type int          $number            Maximum number of sites to retrieve. Default 100.
-	 *     @type int          $offset            Number of sites to offset the query. Used to build LIMIT clause.
-	 *                                           Default 0.
-	 *     @type bool         $no_found_rows     Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
-	 *     @type string|array $orderby           Site status or array of statuses. Accepts 'id', 'domain', 'path',
-	 *                                           'network_id', 'last_updated', 'registered', 'domain_length',
-	 *                                           'path_length', 'site__in' and 'network__in'. Also accepts false,
-	 *                                           an empty array, or 'none' to disable `ORDER BY` clause.
-	 *                                           Default 'id'.
-	 *     @type string       $order             How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'.
-	 *     @type int          $network_id        Limit results to those affiliated with a given network ID. If 0,
-	 *                                           include all networks. Default 0.
-	 *     @type array        $network__in       Array of network IDs to include affiliated sites for. Default empty.
-	 *     @type array        $network__not_in   Array of network IDs to exclude affiliated sites for. Default empty.
-	 *     @type string       $domain            Limit results to those affiliated with a given domain. Default empty.
-	 *     @type array        $domain__in        Array of domains to include affiliated sites for. Default empty.
-	 *     @type array        $domain__not_in    Array of domains to exclude affiliated sites for. Default empty.
-	 *     @type string       $path              Limit results to those affiliated with a given path. Default empty.
-	 *     @type array        $path__in          Array of paths to include affiliated sites for. Default empty.
-	 *     @type array        $path__not_in      Array of paths to exclude affiliated sites for. Default empty.
-	 *     @type int          $public            Limit results to public sites. Accepts '1' or '0'. Default empty.
-	 *     @type int          $archived          Limit results to archived sites. Accepts '1' or '0'. Default empty.
-	 *     @type int          $mature            Limit results to mature sites. Accepts '1' or '0'. Default empty.
-	 *     @type int          $spam              Limit results to spam sites. Accepts '1' or '0'. Default empty.
-	 *     @type int          $deleted           Limit results to deleted sites. Accepts '1' or '0'. Default empty.
-	 *     @type int          $lang_id           Limit results to a language ID. Default empty.
-	 *     @type array        $lang__in          Array of language IDs to include affiliated sites for. Default empty.
-	 *     @type array        $lang__not_in      Array of language IDs to exclude affiliated sites for. Default empty.
-	 *     @type string       $search            Search term(s) to retrieve matching sites for. Default empty.
-	 *     @type array        $search_columns    Array of column names to be searched. Accepts 'domain' and 'path'.
-	 *                                           Default empty array.
-	 *     @type bool         $update_site_cache Whether to prime the cache for found sites. Default true.
+	 *     @type array        $site__in               Array of site IDs to include. Default empty.
+	 *     @type array        $site__not_in           Array of site IDs to exclude. Default empty.
+	 *     @type bool         $count                  Whether to return a site count (true) or array of site objects.
+	 *                                                Default false.
+	 *     @type array        $date_query             Date query clauses to limit sites by. See WP_Date_Query.
+	 *                                                Default null.
+	 *     @type string       $fields                 Site fields to return. Accepts 'ids' (returns an array of site IDs)
+	 *                                                or empty (returns an array of complete site objects). Default empty.
+	 *     @type int          $ID                     A site ID to only return that site. Default empty.
+	 *     @type int          $number                 Maximum number of sites to retrieve. Default 100.
+	 *     @type int          $offset                 Number of sites to offset the query. Used to build LIMIT clause.
+	 *                                                Default 0.
+	 *     @type bool         $no_found_rows          Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
+	 *     @type string|array $orderby                Site status or array of statuses. Accepts 'id', 'domain', 'path',
+	 *                                                'network_id', 'last_updated', 'registered', 'domain_length',
+	 *                                                'path_length', 'site__in' and 'network__in'. Also accepts false,
+	 *                                                an empty array, or 'none' to disable `ORDER BY` clause.
+	 *                                                Default 'id'.
+	 *     @type string       $order                  How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'.
+	 *     @type int          $network_id             Limit results to those affiliated with a given network ID. If 0,
+	 *                                                include all networks. Default 0.
+	 *     @type array        $network__in            Array of network IDs to include affiliated sites for. Default empty.
+	 *     @type array        $network__not_in        Array of network IDs to exclude affiliated sites for. Default empty.
+	 *     @type string       $domain                 Limit results to those affiliated with a given domain. Default empty.
+	 *     @type array        $domain__in             Array of domains to include affiliated sites for. Default empty.
+	 *     @type array        $domain__not_in         Array of domains to exclude affiliated sites for. Default empty.
+	 *     @type string       $path                   Limit results to those affiliated with a given path. Default empty.
+	 *     @type array        $path__in               Array of paths to include affiliated sites for. Default empty.
+	 *     @type array        $path__not_in           Array of paths to exclude affiliated sites for. Default empty.
+	 *     @type int          $public                 Limit results to public sites. Accepts '1' or '0'. Default empty.
+	 *     @type int          $archived               Limit results to archived sites. Accepts '1' or '0'. Default empty.
+	 *     @type int          $mature                 Limit results to mature sites. Accepts '1' or '0'. Default empty.
+	 *     @type int          $spam                   Limit results to spam sites. Accepts '1' or '0'. Default empty.
+	 *     @type int          $deleted                Limit results to deleted sites. Accepts '1' or '0'. Default empty.
+	 *     @type int          $lang_id                Limit results to a language ID. Default empty.
+	 *     @type array        $lang__in               Array of language IDs to include affiliated sites for. Default empty.
+	 *     @type array        $lang__not_in           Array of language IDs to exclude affiliated sites for. Default empty.
+	 *     @type string       $search                 Search term(s) to retrieve matching sites for. Default empty.
+	 *     @type array        $search_columns         Array of column names to be searched. Accepts 'domain' and 'path'.
+	 *                                                Default empty array.
+	 *     @type bool         $update_site_cache      Whether to prime the cache for found sites. Default true.
+	 *     @type bool         $update_site_meta_cache Whether to prime the metadata cache for found sites. Default true.
+	 *     @type array        $meta_query             Meta query clauses to limit retrieved sites by. See `WP_Meta_Query`.
+	 *                                                Default empty.
+	 *     @type string       $meta_key               Limit sites to those matching a specific metadata key.
+	 *                                                Can be used in conjunction with `$meta_value`. Default empty.
+	 *     @type string       $meta_value             Limit sites to those matching a specific metadata value.
+	 *                                                Usually used in conjunction with `$meta_key`. Default empty.
+	 *     @type string       $meta_type              Data type that the `$meta_value` column will be CAST to for
+	 *                                                comparisons. Default empty.
+	 *     @type string       $meta_compare           Comparison operator to test the `$meta_value`. Default empty.
 	 * }
 	 */
 	public function __construct( $query = '' ) {
 		$this->query_var_defaults = array(
-			'fields'            => '',
-			'ID'                => '',
-			'site__in'          => '',
-			'site__not_in'      => '',
-			'number'            => 100,
-			'offset'            => '',
-			'no_found_rows'     => true,
-			'orderby'           => 'id',
-			'order'             => 'ASC',
-			'network_id'        => 0,
-			'network__in'       => '',
-			'network__not_in'   => '',
-			'domain'            => '',
-			'domain__in'        => '',
-			'domain__not_in'    => '',
-			'path'              => '',
-			'path__in'          => '',
-			'path__not_in'      => '',
-			'public'            => null,
-			'archived'          => null,
-			'mature'            => null,
-			'spam'              => null,
-			'deleted'           => null,
-			'lang_id'           => null,
-			'lang__in'          => '',
-			'lang__not_in'      => '',
-			'search'            => '',
-			'search_columns'    => array(),
-			'count'             => false,
-			'date_query'        => null, // See WP_Date_Query
-			'update_site_cache' => true,
+			'fields'                 => '',
+			'ID'                     => '',
+			'site__in'               => '',
+			'site__not_in'           => '',
+			'number'                 => 100,
+			'offset'                 => '',
+			'no_found_rows'          => true,
+			'orderby'                => 'id',
+			'order'                  => 'ASC',
+			'network_id'             => 0,
+			'network__in'            => '',
+			'network__not_in'        => '',
+			'domain'                 => '',
+			'domain__in'             => '',
+			'domain__not_in'         => '',
+			'path'                   => '',
+			'path__in'               => '',
+			'path__not_in'           => '',
+			'public'                 => null,
+			'archived'               => null,
+			'mature'                 => null,
+			'spam'                   => null,
+			'deleted'                => null,
+			'lang_id'                => null,
+			'lang__in'               => '',
+			'lang__not_in'           => '',
+			'search'                 => '',
+			'search_columns'         => array(),
+			'count'                  => false,
+			'date_query'             => null, // See WP_Date_Query
+			'update_site_cache'      => true,
+			'update_site_meta_cache' => true,
+			'meta_query'             => '',
+			'meta_key'               => '',
+			'meta_value'             => '',
+			'meta_type'              => '',
+			'meta_compare'           => '',
 		);
 
 		if ( ! empty( $query ) ) {
@@ -225,12 +259,20 @@
 	 *
 	 * @since 4.6.0
 	 *
+	 * @global wpdb $wpdb WordPress database abstraction object.
+	 *
 	 * @return array|int List of WP_Site objects, a list of site ids when 'fields' is set to 'ids',
 	 *                   or the number of sites when 'count' is passed as a query var.
 	 */
 	public function get_sites() {
+		global $wpdb;
+
 		$this->parse_query();
 
+		// Parse meta query.
+		$this->meta_query = new WP_Meta_Query();
+		$this->meta_query->parse_query_vars( $this->query_vars );
+
 		/**
 		 * Fires before sites are retrieved.
 		 *
@@ -240,32 +282,57 @@
 		 */
 		do_action_ref_array( 'pre_get_sites', array( &$this ) );
 
-		// $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
-		$_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
+		// Reparse query vars, in case they were modified in a 'pre_get_sites' callback.
+		$this->meta_query->parse_query_vars( $this->query_vars );
+		if ( ! empty( $this->meta_query->queries ) ) {
+			$this->meta_query_clauses = $this->meta_query->get_sql( 'blog', $wpdb->blogs, 'blog_id', $this );
+		}
 
-		// Ignore the $fields argument as the queried result will be the same regardless.
-		unset( $_args['fields'] );
+		$site_ids = null;
 
-		$key = md5( serialize( $_args ) );
-		$last_changed = wp_cache_get_last_changed( 'sites' );
+		/**
+		 * Filter the sites array before the query takes place.
+		 *
+		 * Return a non-null value to bypass WordPress's default site queries.
+		 *
+		 *
+		 * @since 5.2.0
+		 *
+		 * @param array|null    $site_ids Return an array of site data to short-circuit WP's site query,
+		 *                                or null to allow WP to run its normal queries.
+		 * @param WP_Site_Query $this The WP_Site_Query instance, passed by reference.
+		 */
+		$site_ids = apply_filters_ref_array( 'sites_pre_query', array( $site_ids, &$this ) );
 
-		$cache_key = "get_sites:$key:$last_changed";
-		$cache_value = wp_cache_get( $cache_key, 'sites' );
+		if ( null === $site_ids ) {
 
-		if ( false === $cache_value ) {
-			$site_ids = $this->get_site_ids();
-			if ( $site_ids ) {
-				$this->set_found_sites();
-			}
+			// $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
+			$_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
+
+			// Ignore the $fields argument as the queried result will be the same regardless.
+			unset( $_args['fields'] );
+
+			$key          = md5( serialize( $_args ) );
+			$last_changed = wp_cache_get_last_changed( 'sites' );
+
+			$cache_key   = "get_sites:$key:$last_changed";
+			$cache_value = wp_cache_get( $cache_key, 'sites' );
 
-			$cache_value = array(
-				'site_ids' => $site_ids,
-				'found_sites' => $this->found_sites,
-			);
-			wp_cache_add( $cache_key, $cache_value, 'sites' );
-		} else {
-			$site_ids = $cache_value['site_ids'];
-			$this->found_sites = $cache_value['found_sites'];
+			if ( false === $cache_value ) {
+				$site_ids = $this->get_site_ids();
+				if ( $site_ids ) {
+					$this->set_found_sites();
+				}
+
+				$cache_value = array(
+					'site_ids'    => $site_ids,
+					'found_sites' => $this->found_sites,
+				);
+				wp_cache_add( $cache_key, $cache_value, 'sites' );
+			} else {
+				$site_ids          = $cache_value['site_ids'];
+				$this->found_sites = $cache_value['found_sites'];
+			}
 		}
 
 		if ( $this->found_sites && $this->query_vars['number'] ) {
@@ -288,7 +355,7 @@
 
 		// Prime site network caches.
 		if ( $this->query_vars['update_site_cache'] ) {
-			_prime_site_caches( $site_ids );
+			_prime_site_caches( $site_ids, $this->query_vars['update_site_meta_cache'] );
 		}
 
 		// Fetch full site objects from the primed cache.
@@ -304,7 +371,7 @@
 		 *
 		 * @since 4.6.0
 		 *
-		 * @param array         $_sites An array of WP_Site objects.
+		 * @param WP_Site[]     $_sites An array of WP_Site objects.
 		 * @param WP_Site_Query $this   Current instance of WP_Site_Query (passed by reference).
 		 */
 		$_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) );
@@ -345,10 +412,10 @@
 
 				if ( is_int( $_key ) ) {
 					$_orderby = $_value;
-					$_order = $order;
+					$_order   = $order;
 				} else {
 					$_orderby = $_key;
-					$_order = $_value;
+					$_order   = $_value;
 				}
 
 				$parsed = $this->parse_orderby( $_orderby );
@@ -367,11 +434,12 @@
 
 			$orderby = implode( ', ', $orderby_array );
 		} else {
-			$orderby = "blog_id $order";
+			$orderby = "{$wpdb->blogs}.blog_id $order";
 		}
 
 		$number = absint( $this->query_vars['number'] );
 		$offset = absint( $this->query_vars['offset'] );
+		$limits = '';
 
 		if ( ! empty( $number ) ) {
 			if ( $offset ) {
@@ -384,23 +452,23 @@
 		if ( $this->query_vars['count'] ) {
 			$fields = 'COUNT(*)';
 		} else {
-			$fields = 'blog_id';
+			$fields = "{$wpdb->blogs}.blog_id";
 		}
 
 		// Parse site IDs for an IN clause.
 		$site_id = absint( $this->query_vars['ID'] );
 		if ( ! empty( $site_id ) ) {
-			$this->sql_clauses['where']['ID'] = $wpdb->prepare( 'blog_id = %d', $site_id );
+			$this->sql_clauses['where']['ID'] = $wpdb->prepare( "{$wpdb->blogs}.blog_id = %d", $site_id );
 		}
 
 		// Parse site IDs for an IN clause.
 		if ( ! empty( $this->query_vars['site__in'] ) ) {
-			$this->sql_clauses['where']['site__in'] = "blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
+			$this->sql_clauses['where']['site__in'] = "{$wpdb->blogs}.blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
 		}
 
 		// Parse site IDs for a NOT IN clause.
 		if ( ! empty( $this->query_vars['site__not_in'] ) ) {
-			$this->sql_clauses['where']['site__not_in'] = "blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
+			$this->sql_clauses['where']['site__not_in'] = "{$wpdb->blogs}.blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
 		}
 
 		$network_id = absint( $this->query_vars['network_id'] );
@@ -448,33 +516,33 @@
 		}
 
 		if ( is_numeric( $this->query_vars['archived'] ) ) {
-			$archived = absint( $this->query_vars['archived'] );
-			$this->sql_clauses['where']['archived'] = $wpdb->prepare( "archived = %s ", absint( $archived ) );
+			$archived                               = absint( $this->query_vars['archived'] );
+			$this->sql_clauses['where']['archived'] = $wpdb->prepare( 'archived = %s ', absint( $archived ) );
 		}
 
 		if ( is_numeric( $this->query_vars['mature'] ) ) {
-			$mature = absint( $this->query_vars['mature'] );
-			$this->sql_clauses['where']['mature'] = $wpdb->prepare( "mature = %d ", $mature );
+			$mature                               = absint( $this->query_vars['mature'] );
+			$this->sql_clauses['where']['mature'] = $wpdb->prepare( 'mature = %d ', $mature );
 		}
 
 		if ( is_numeric( $this->query_vars['spam'] ) ) {
-			$spam = absint( $this->query_vars['spam'] );
-			$this->sql_clauses['where']['spam'] = $wpdb->prepare( "spam = %d ", $spam );
+			$spam                               = absint( $this->query_vars['spam'] );
+			$this->sql_clauses['where']['spam'] = $wpdb->prepare( 'spam = %d ', $spam );
 		}
 
 		if ( is_numeric( $this->query_vars['deleted'] ) ) {
-			$deleted = absint( $this->query_vars['deleted'] );
-			$this->sql_clauses['where']['deleted'] = $wpdb->prepare( "deleted = %d ", $deleted );
+			$deleted                               = absint( $this->query_vars['deleted'] );
+			$this->sql_clauses['where']['deleted'] = $wpdb->prepare( 'deleted = %d ', $deleted );
 		}
 
 		if ( is_numeric( $this->query_vars['public'] ) ) {
-			$public = absint( $this->query_vars['public'] );
-			$this->sql_clauses['where']['public'] = $wpdb->prepare( "public = %d ", $public );
+			$public                               = absint( $this->query_vars['public'] );
+			$this->sql_clauses['where']['public'] = $wpdb->prepare( 'public = %d ', $public );
 		}
 
 		if ( is_numeric( $this->query_vars['lang_id'] ) ) {
-			$lang_id = absint( $this->query_vars['lang_id'] );
-			$this->sql_clauses['where']['lang_id'] = $wpdb->prepare( "lang_id = %d ", $lang_id );
+			$lang_id                               = absint( $this->query_vars['lang_id'] );
+			$this->sql_clauses['where']['lang_id'] = $wpdb->prepare( 'lang_id = %d ', $lang_id );
 		}
 
 		// Parse site language IDs for an IN clause.
@@ -506,7 +574,7 @@
 			 *
 			 * @since 4.6.0
 			 *
-			 * @param array         $search_columns Array of column names to be searched.
+			 * @param string[]      $search_columns Array of column names to be searched.
 			 * @param string        $search         Text being searched.
 			 * @param WP_Site_Query $this           The current WP_Site_Query instance.
 			 */
@@ -517,11 +585,23 @@
 
 		$date_query = $this->query_vars['date_query'];
 		if ( ! empty( $date_query ) && is_array( $date_query ) ) {
-			$this->date_query = new WP_Date_Query( $date_query, 'registered' );
+			$this->date_query                         = new WP_Date_Query( $date_query, 'registered' );
 			$this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
 		}
 
-		$join = '';
+		$join    = '';
+		$groupby = '';
+
+		if ( ! empty( $this->meta_query_clauses ) ) {
+			$join .= $this->meta_query_clauses['join'];
+
+			// Strip leading 'AND'.
+			$this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
+
+			if ( ! $this->query_vars['count'] ) {
+				$groupby = "{$wpdb->blogs}.blog_id";
+			}
+		}
 
 		$where = implode( ' AND ', $this->sql_clauses['where'] );
 
@@ -532,16 +612,16 @@
 		 *
 		 * @since 4.6.0
 		 *
-		 * @param array         $pieces A compacted array of site query clauses.
+		 * @param string[]      $pieces An associative array of site query clauses.
 		 * @param WP_Site_Query $this   Current instance of WP_Site_Query (passed by reference).
 		 */
 		$clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) );
 
-		$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
-		$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
-		$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
+		$fields  = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
+		$join    = isset( $clauses['join'] ) ? $clauses['join'] : '';
+		$where   = isset( $clauses['where'] ) ? $clauses['where'] : '';
 		$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
-		$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
+		$limits  = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
 		$groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
 
 		if ( $where ) {
@@ -611,8 +691,8 @@
 	 *
 	 * @global wpdb  $wpdb WordPress database abstraction object.
 	 *
-	 * @param string $string  Search string.
-	 * @param array  $columns Columns to search.
+	 * @param string   $string  Search string.
+	 * @param string[] $columns Array of columns to search.
 	 * @return string Search SQL.
 	 */
 	protected function get_search_sql( $string, $columns ) {
@@ -650,11 +730,11 @@
 		switch ( $orderby ) {
 			case 'site__in':
 				$site__in = implode( ',', array_map( 'absint', $this->query_vars['site__in'] ) );
-				$parsed = "FIELD( {$wpdb->blogs}.blog_id, $site__in )";
+				$parsed   = "FIELD( {$wpdb->blogs}.blog_id, $site__in )";
 				break;
 			case 'network__in':
 				$network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
-				$parsed = "FIELD( {$wpdb->blogs}.site_id, $network__in )";
+				$parsed      = "FIELD( {$wpdb->blogs}.site_id, $network__in )";
 				break;
 			case 'domain':
 			case 'last_updated':
@@ -672,10 +752,42 @@
 				$parsed = 'CHAR_LENGTH(path)';
 				break;
 			case 'id':
-				$parsed = 'blog_id';
+				$parsed = "{$wpdb->blogs}.blog_id";
 				break;
 		}
 
+		if ( ! empty( $parsed ) || empty( $this->meta_query_clauses ) ) {
+			return $parsed;
+		}
+
+		$meta_clauses = $this->meta_query->get_clauses();
+		if ( empty( $meta_clauses ) ) {
+			return $parsed;
+		}
+
+		$primary_meta_query = reset( $meta_clauses );
+		if ( ! empty( $primary_meta_query['key'] ) && $primary_meta_query['key'] === $orderby ) {
+			$orderby = 'meta_value';
+		}
+
+		switch ( $orderby ) {
+			case 'meta_value':
+				if ( ! empty( $primary_meta_query['type'] ) ) {
+					$parsed = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
+				} else {
+					$parsed = "{$primary_meta_query['alias']}.meta_value";
+				}
+				break;
+			case 'meta_value_num':
+				$parsed = "{$primary_meta_query['alias']}.meta_value+0";
+				break;
+			default:
+				if ( isset( $meta_clauses[ $orderby ] ) ) {
+					$meta_clause = $meta_clauses[ $orderby ];
+					$parsed      = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
+				}
+		}
+
 		return $parsed;
 	}