按多个值排序GET_TERMS

时间:2019-03-07 作者:Roman Sarvarov

get\\u terms()的Orderby不接受数组类型。如何使此代码工作?

$allcities = get_terms( array(
    \'taxonomy\' => \'city\',
    \'hide_empty\' => false,
    \'orderby\' => array( \'meta_value_num\' => \'ASC\', \'count\' => \'ASC\' ), 
    \'meta_query\' => array( 
        array(
        \'key\' => \'country\',
        \'type\' => \'NUMERIC\',
        )
    ),
) );

2 个回复
SO网友:Jacob Peattie

WP_Term_Query, 哪些权力get_terms(), 不支持以相同方式按多个属性排序WP_Query

但是,由于不需要担心分页,因此可以在查询结果后对其进行排序,从而获得所需的结果:

$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;
} );

SO网友:Roman Sarvarov

Jacob的方法很有效,但我发现了一种更好的方法(我认为),只使用一个sql请求。

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;