WP_Site_Query::parse_orderby()protectedWP 4.6.0

Parses and sanitizes 'orderby' keys passed to the site query.

Method of the class: WP_Site_Query{}

No Hooks.

Return

String|false. Value to used in the ORDER clause. False otherwise.

Usage

// protected - for code of main (parent) or child class
$result = $this->parse_orderby( $orderby );
$orderby(string) (required)
Alias for the field to order by.

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 4.6.0 Introduced.

WP_Site_Query::parse_orderby() code WP 6.6.2

protected function parse_orderby( $orderby ) {
	global $wpdb;

	$parsed = false;

	switch ( $orderby ) {
		case 'site__in':
			$site__in = implode( ',', array_map( 'absint', $this->query_vars['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 )";
			break;
		case 'domain':
		case 'last_updated':
		case 'path':
		case 'registered':
		case 'deleted':
		case 'spam':
		case 'mature':
		case 'archived':
		case 'public':
			$parsed = $orderby;
			break;
		case 'network_id':
			$parsed = 'site_id';
			break;
		case 'domain_length':
			$parsed = 'CHAR_LENGTH(domain)';
			break;
		case 'path_length':
			$parsed = 'CHAR_LENGTH(path)';
			break;
		case '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;
}