Mathieu Hays

Since WordPress 4.0, in WP_Query, we were able to pass an array in ‘orderby‘ to be able to order by multiple column but we weren’t able to pass more than one custom post meta. With the 4.2 release, we are now able to use as many as we want !

With 4.0 we just had to specify a ‘meta_key‘ to be able to order ‘meta_value‘ but now we have to register the custom meta using the ‘meta_query‘ so we can use their key as reference.

<?php

$args = array(
  'post_type' => 'my_post_type',
  'posts_per_page' => 10,
  'meta_query' => array(
    'custom_key' => array(
      'key' => 'custom_meta',
      'compare' => 'EXISTS'
    ),
    'other_key' => array(
      'key' => 'other_meta',
      'compare' => 'EXISTS'
    )
  ),
  'orderby' => array(
    'custom_key' => 'DESC',
    'other_key' => 'ASC',
    'title' => 'ASC'
  )
);

$my_custom_query = new WP_Query($args);

if ($my_custom_query->have_posts()) {
  while ($my_custom_query->have_posts()) {
    $my_custom_query->the_post();

    // Do stuff
    the_title();
  }
}

wp_reset_postdata();

The keys ‘custom_key’ and ‘other_key’ can be any non-reserved name you want, they act like variables here.

You can’t use the following names: ‘none’, ‘name’, ‘author’, ‘date’, ‘title’, ‘modified’, ‘menu_order’, ‘parent’, ‘ID’, ‘rand’, ‘comment_count’, ‘meta_value’, ‘meta_value_num’