Order get_terms using a Custom Field

I have a custom taxonomy of “crb_issues” that has a custom field associated with it that is “issue_date” which outputs a date value for each term to looks a lot like “20140601” yearmonthday.

I am trying to out put all the Taxonomies terms using get_terms and order them by that custom field. Below is the code I have been working on which outputs the Terms Name and the value of the “issue_date” just fine. But I am having a hard time getting what is outputting to order by that custom field.

$args = array(
    'meta_key'          => 'issue_date',
    'orderby'           => 'meta_value_num', 
    'order'             => 'DESC',
    'hide_empty'        => true,
    'number'            => '4', 
    'fields'            => 'all', 
); 

$terms = get_terms("crb_issues", $args);

 if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    echo "<ul>";
    foreach ( $terms as $term ) {
        echo "<li>" . $term->name . "</li>";
        the_field('issue_date', $term);
    }
    echo "</ul>";
 }

Any help would be much appreciated.

6 s
6

Rather than outputting your terms in that initial loop, I would use it instead to build a new array, with your issue_date as the key:

$my_new_array = array( );
foreach ( $terms as $term ) {
    $issue_date = get_field( 'issue_date', $term );
    $my_new_array[$issue_date] = $term->name;
}

You can then loop through this new array in order:

ksort( $my_new_array, SORT_NUMERIC );

foreach ( $my_new_array as $issue_date => $term_name ) {
   echo "<li>" . $term_name . " " . $issue_date . "</li>";
}

This is untested.

Leave a Comment