Orderby of get_terms() does not accept array type. How do I make this code works?

$allcities = get_terms( array(
    'taxonomy' => 'city',
    'hide_empty' => false,
    'orderby' => array( 'meta_value_num' => 'ASC', 'count' => 'ASC' ), 
    'meta_query' => array( 
        'key' => 'country',
        'type' => 'NUMERIC',
) );
  • Get terms in any order and sort the result using usort(), for example. – Max Yudin Mar 7 '19 at 7:37

WP_Term_Query, which powers get_terms(), does not support ordering by multiple properties the same way WP_Query does.

But, since you don't need to worry about pagination, you'll be able to achieve the result you want by sorting the results after querying them:

$allcities = get_terms( array(
    'taxonomy'   => 'city',
    'hide_empty' => false,
) );

usort( $allcities, function( $a, $b ) {
    $a_country = (int) get_term_meta( $a->term_id, 'country', true );
    $b_country = (int) get_term_meta( $b->term_id, 'country', true );

    return $a_country - $b_country ?: $a->count - $count;
} );
| improve this answer | |

Jacob's method works, but I found a better way (I think) by using only one sql request.

SELECT DISTINCT t.*, tt.*, tr.meta_value as country
        FROM $wpdb->terms AS t 
        INNER JOIN $wpdb->termmeta
        ON ( t.term_id = $wpdb->termmeta.term_id )
        INNER JOIN $wpdb->term_taxonomy AS tt
        ON t.term_id = tt.term_id
        INNER JOIN $wpdb->termmeta AS tr
        ON t.term_id = tr.term_id
        WHERE tt.taxonomy IN ('city')
        AND tr.meta_key = 'country'
        ORDER BY cast(country AS unsigned) ASC, tt.count DESC;
| improve this answer | |

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.