Order WordPress Terms by Term Meta: https://wordpress.org/plugins/advanced-term-fields/
<?php
/**
* Filter the terms query SQL clauses.
*
* @see 'terms_clauses' filter in get_terms() wp-includes/taxonomy.php
*
* @since 0.1.0
*
* @todo add filter for $allowed_orderby_keys
*
* @param array $pieces Terms query SQL clauses.
* @param array $taxonomies An array of taxonomies.
* @param array $args An array of terms query arguments.
*
* @return array $pieces The filtered SQL clauses
*/
function filter_terms_clauses( $pieces = array(), $taxonomies = array(), $args = array() )
{
global $wpdb;
/**
* If we're not ordering by any of the allowed keys, return
*/
$orderby = ( ! empty( $args['orderby'] ) ) ? $args['orderby'] : '' ;
$allowed_orderby_keys = array( 'meta_value', 'meta_value_num' );
if ( ! in_array( $orderby, $allowed_orderby_keys, true ) ) {
return $pieces ;
}
// Bail if there's no meta query
if( empty( $args['meta_query'] ) ) {
return $pieces ;
}
switch ( $args[ 'orderby' ] ) {
case 'meta_value' :
$pieces ['orderby'] = "ORDER BY {$wpdb->termmeta}.meta_value";
break;
case 'meta_value_num':
$pieces ['orderby'] = "ORDER BY {$wpdb->termmeta}.meta_value+0";
break;
}
return $pieces ;
}
add_filter( 'terms_clauses', array($this, 'filter_terms_clauses'), 10, 3 );
/**
* Call your terms like so:
*
* Replace "my_meta_key" with the name of the requested meta key
*/
$args = array(
'hide_empty' => false,
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'OR',
array(
'key'=>'my_meta_key',
'compare' => 'EXISTS'
),
array(
'key'=>'my_meta_key',
'compare' => 'NOT EXISTS'
)
),
);
get_terms($taxonomy, $args);