Is there a way to do multiple ordering on a multiple meta_query?

As of WordPress 3.4.1, there is no way, out of the box, to order by multiple meta values.

Since we can’t do it cleanly, we’ll have to hack something together. We can hook into posts_orderby to manually modify the ordering. It’s not altogether pretty, but it will get the job done. Here’s an example:

add_filter('posts_orderby', 'wpse_28390_orderby' );
function wpse_28390_orderby( $orderby ) {
    return str_replace('postmeta.meta_value', 'postmeta.meta_value, mt1.meta_value ASC', $orderby);
}

Most importantly, this assumes that “surface” is the second meta_key in your query (that’s where mt1 comes from; mt1 is the second meta key, mt2 is the third, and so on), which in your case won’t always be correct. Therefore, the add_filter call should go behind three checks:

  1. if this is the page where this would be relevant,
  2. if the surface meta_key is being queried (if the $_GET param is present), and
  3. which number the surface meta_key is in the join sequence, then adjust mt1 accordingly

It’s janky, but again, it will work.

Leave a Comment