0

I have small issue with orderby. I´m looking solution to orderby ASC (lastname + firstname) example:

  1. Selanne Andy
  2. Selanne Beeny
  3. Selanne Teemu

But now it arrays something like this:

  1. Selanne Beeny
  2. Selanne Teemu
  3. Selanne Andy

Here is code:

$order_by_1 = array(
    'meta_key'  => 'last_name',
    'meta_query' => array(
      array(
          'key' => 'last_name',
          'orderby' => 'meta_value',
          'order'    => 'ASC'
      ),
      array(
          'key' => 'first_name',
          'orderby' => 'meta_value',
          'order'    => 'ASC'
      ),
    ),                      
    'orderby'   => 'meta_value',
    'order'     => 'ASC'
);                      



$usr_1 = get_users($order_by_1);

// Array of stdClass objects.
foreach ( $usr_1 as $user ) { ....

Thanks for the help.

1 Answer 1

1

To do this you need to use named meta query clauses according to the official developer docs for WP_Query:

‘orderby’ with multiple ‘meta_key’s

If you wish to order by two different pieces of postmeta (for example, City first and State second), you need to combine and link your meta query to your orderby array using ‘named meta queries’. See the example below:

    'meta_query' => array(
        'relation' => 'AND',
        'state_clause' => array(
            'key' => 'state',
            'value' => 'Wisconsin',
        ),
        'city_clause' => array(
            'key' => 'city',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array( 
        'city_clause' => 'ASC',
        'state_clause' => 'DESC',
    ), ) ); ```

https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

This question was also asked and answered already here:

Order by multiple meta key and meta value

1
  • 1
    Awsome, thank you! I got this working!
    – MSI
    Commented Nov 9, 2021 at 11:20

Your Answer

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

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