WP_Query_Multisite icon indicating copy to clipboard operation
WP_Query_Multisite copied to clipboard

How to order by post_meta?

Open jasmines opened this issue 5 years ago • 2 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?

jasmines avatar Dec 12 '19 08:12 jasmines

+1

iversoncreative avatar May 12 '20 05:05 iversoncreative

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.

cr0ybot avatar Apr 10 '21 20:04 cr0ybot