admin管理员组

文章数量:1323714

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?

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?

Share Improve this question edited Sep 11, 2020 at 2:09 Cyclonecode 1,1841 gold badge9 silver badges32 bronze badges asked Sep 10, 2020 at 19:50 NotaGuruAtAllNotaGuruAtAll 1011 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 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.

本文标签: Query by meta key and order by another meta key value