WP_Query sort by multiple custom fields

WP_Query doesn’t natively support sorting by multiple custom fields. However, this is possible with a little customization and the posts_orderby filter.

The first step is to modify your query args. The “meta_query” section should contain the custom fields you want to sort by. Also, notice that we added a custom sort_custom argument. This will be important in a moment.

$args = [
  'post_type' => 'post',
  'post_status' => 'publish',
  'sort_custom' => true,
  'meta_query' => [
      'key' => 'custom_field_1',
      'key' => 'custom_field_2',

// Run the query at some point
$query = new WP_Query( $args );

Next, add the following code to your theme’s functions.php. We want to override the orderby only if sort_custom exists. In this example, we’re sorting the first custom field in ASC order, then the second field in DESC order.

function mysite_custom_sort( $orderby, $wp_query ) {
  if ( isset( $wp_query->query_vars['sort_custom'] ) ) {
    $orderby = 'mt1.meta_value ASC, mt2.meta_value DESC';
  return $orderby;
add_filter( 'posts_orderby', 'mysite_custom_sort', 10, 2 );