WP-Query order by two meta values

If you want to order a custom WP-Query by two meta values you can add a function via a filter that modifies the query. Define the meta values in your query arguments and then refer to them in the filter with “mt1” for the first meta and “mt2” for the second one.


$args = array(
'posts_per_page'	=> -1, 
'offset'			=> 0,
'post_type'			=> 'post', 
'post_status'		=> 'publish',
'order'				=> 'DESC', 
'meta_key'     => 'price',
'meta_query'   => array(
	array(
	'key' => 'price'
	),
	array(
	'key' => 'amount'
	)
)
);

function customorderby($orderby) {
	return 'mt1.meta_value DESC, mt2.meta_value+0 DESC';
}
add_filter('posts_orderby','customorderby');
$query = new WP_Query( $args );
remove_filter('posts_orderby','customorderby');