1

I'm looking to find a way to order my query by Last Name first then First Name. I was able to do Last Name although not much luck in the Last Name + First Name part. This is what I came up:

$posts = get_posts(
    [
        'post_type'      => 'soldier',
        'post_status'    => 'publish',
        'posts_per_page' => 5,
        'meta_key'       => 'last_name',
        'orderby'        => 'meta_value',
        'order'          => 'DESC',
        'meta_query'     => [
            [
                'key'     => 'last_name',
                'orderby' => 'meta_value',
                'order'   => ASC
            ],
            [
                'key'     => 'first_name',
                'orderby' => 'meta_value',
                'order'   => ASC
            ],
        ],
        'paged'          => $soldier_paged
    ]
);
1

Your code has a few issues, some unrelated, but generally, you need named meta queries to order by multiple meta keys:

$posts = get_posts( [
    'post_type'      => 'soldier',
    'posts_per_page' => 5,
    'paged'          => $soldier_paged,
    'meta_query'     => [
        'last_name_clause'  => [
            'key'     => 'last_name',
            'compare' => 'EXISTS'
        ],
        'first_name_clause' => [
            'key'     => 'first_name',
            'compare' => 'EXISTS'
        ],
    ],

    'orderby' => [
        'last_name_clause'  => 'ASC',
        'first_name_clause' => 'ASC',
    ],
] );
  • Hi, it works great! Thanks! Although don't know what you meant by some few issues? – Mark Anthony Sep 24 '18 at 18:36
  • just order and orderby were in the wrong place inside meta_query- not breaking anything, just not doing anything. also, for arguments like post_status, I leave it out if it's the default value. – Milo Sep 24 '18 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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