badcrocodile
2/20/2015 - 3:45 AM

Order WP_Query by multiple custom fields

Order WP_Query by multiple custom fields

<?php
// Sourced from very smart person at http://www.smartcode.ch/blog/order-posts-in-wordpress-by-multiple-custom-fields/
/**
 * Sort by custom fields.
 * mt1 refers to meta_1, mt2 to meta_2 and mt3 to meta_3
 *
 * @param $orderby original order by string
 * @return custom order by string 
 */
function customorderby($orderby) {
    return 'mt1.meta_value, mt2.meta_value DESC';
}

// Example usage. Note lack of orderby and additional meta_key.
$args = array(
	'post_type' => 'event',
	'meta_key' => 'date',
	'meta_query' => array(
		array(
			'key' => 'date',
		),
		array(
			'key' => 'time',
		),
	),
	'posts_per_page' => -1
);

add_filter('posts_orderby','customorderby');
$event_query = new WP_Query($args);
remove_filter('posts_orderby','customorderby');
?>