miguelpeixe / WP_Query_Multisite

A subclass of WP_Query to allow for easy querying of multisite posts

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to order by post_meta?

jasmines opened this issue · comments

If I try to add

$args['meta_key'] = 'my_meta_key';
$args['orderby'] = 'meta_value';
$args['order'] = 'DESC';

the query results NULL, because postmeta table is not in the main fields of the query...

How can I solve?

This class saved my butt but I did have to modify it for this reason.

I had to inject the ORDER BY clause inside the UNION block, and had to remove the table name in order for that to work.

Line 64 became:

$meta_value = $query->get('orderby') === 'meta_value' ? ', meta_value ' : '';
$ms_select = " SELECT $wpdb->posts.*, '$site_id' as site_id $meta_value FROM $wpdb->posts $ms_select ";

Line 78:

// Special case for meta_value
if ( $query->get('orderby') === 'meta_value' ) {
	// If there is a meta_value query, remove the table name
	$clauses['orderby'] = str_replace( $wpdb->postmeta . '.', '', $clauses['orderby'] );

	// Insert orderby clause onto end of ms_select
	$this->ms_select[count($this->ms_select) - 1] .= " ORDER BY {$clauses['orderby']} ";
	// Remove main orderby
	$clauses['orderby'] = '';
}
else {
	// Orderby for tables (not wp_posts)
	$clauses['orderby'] = str_replace( $wpdb->posts, 'tables', $clauses['orderby'] );
}

This solution is very specific to orderby => meta_value.