0

I have a query that looks like this:

$orders = get_posts( array(
    'numberofposts'     => -1,
    'posts_per_page'    => -1,
    'post_type'         => 'executive-orders',
    'meta_key'          => 'eo_type',
    'meta_value'        => 'county',
    'orderby'           => 'date',
    'order'             => 'DESC',
));

And I would like to order by another meta key value. I am aware you can do this:

'orderby' => 'meta_value_num',

But is it possible to do both?

1 Answer 1

1

You can do this with a meta_query. The get_posts() function accepts everything that WP_Query accepts so it could look something like this:

$orders = get_posts( array(
    'numberofposts'     => -1,
    'posts_per_page'    => -1,
    'post_type'         => 'executive-orders',
    'orderby'           => 'date',
    'order'             => 'DESC',
    'meta_query'    => array(
        'relation' => 'AND',
        'eo_type' => array(
            'key'       => 'eo_type',
            'value' => 'county',
        ),
        'second_type' => array(
            'key'   => 'second_key',
            'type'  => 'NUMERIC',
        ),
    ),
    'orderby' => array( 'eo_type' => 'DESC', 'date' => 'ASC' ),
) );

With the Meta Query we can define our key value pairs just like we did with meta_key and meta_value. We give them a named index eo_type so that we can reference it in the orderby parameter. We can add as many meta values as we need and can even nest further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.