WP_Query_Multisite
WP_Query_Multisite copied to clipboard
How to order by post_meta?
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?
+1
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
.