Wordpress - Custom query with orderby meta_value of custom field

You can define the meta key for orderby parameter using the old method (I tested on WP 3.1.1)...

query_posts(
    array(  'post_type' => 'services',
            'order'     => 'ASC',
            'meta_key' => 'some_key',
            'orderby'   => 'meta_value', //or 'meta_value_num'
            'meta_query' => array(
                                array('key' => 'order_in_archive',
                                      'value' => 'some_value'
                                )
                            )
    )
);

This issue in general is cleared up in WordPress 4.2 by using named queries. e.g.

$args = array(
  'post_type' => 'services',
  'orderby'   => 'order_clause',
  'meta_query' => array(
       'order_clause' => array(
            'key' => 'order_in_archive',
            'value' => 'some_value',
            'type' => 'NUMERIC' // unless the field is not a number
)));

For me, I wanted to order by a numeric field and I had to use 'type' => 'NUMERIC' inside the meta query.


The WP Codex is actually confusing when addressing this problem.

You do not actually need the meta_query param to use the orderby, instead it uses the meta_key param, which although by WP Codex is deprecated is has been established here: How do you use orderby with meta_query in Wordpress 3.1? that orderyby still needs the meta_key.

so it should be

query_posts( array(
  'post_type' => 'services',
  'order' => 'ASC',
  'orderby' => 'meta_value',
  'meta_key' => 'order_in_archive'
) )