Custom query with orderby meta_value of custom field

  • Aa you know, as of WP3.0 there are options for custom advanced queries, which is great. As of this, some query parameters of custom fields like meta_key, meta_value were deprecated for the new meta_query parameter (see here)

    I try to have a pretty simple query with the new syntax, query posts by a certain post_type (services) that contains a specified meta_key (order_in_archive)- this is going well as expected. But - I want to orderby the query by the meta_value, and with no success.

    This is my query -

       query_posts(
        array(  'post_type' => 'services',
            'order' => 'ASC',
            'orderby' => 'meta_value',
            'meta_query' => array(
                array('key' => 'order_in_archive'))
        )
    );
    

    I tried orderby also by meta_value_numeric and meta_value, but in any case the results are being ordered by the publication date (as regular posts do). Anyone know how can this be done?

    Thanks

  • 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'
                                    )
                                )
        )
    );
    

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM