Support

Account

Home Forums General Issues Order by ACF Reply To: Order by ACF

  • You can’t order terms by a custom field.

    orderby for get_terms() only accepts one of the argument listed on the codex page https://codex.wordpress.org/Function_Reference/get_terms

    In order to do this you need to get the terms, then loop through the terms, get your custom field and add it to each term object and then build a PHP function to order them.

    I’ve done this a few times

    
    function my_sort_function($a, $b) {
        if ($a->star_rating == $b->star_rating) {
            return 0;
        } elseif ($a->star_rating < $b->star_rating) {
            return -1;
        } else {
            return 1;
        }
    }
    
    $terms = get_terms($taxonomy, $args);
    if ($terms) {
        foreach ($terms as $index => $term) {
            $terms[$index]->star_rating = get_field('star_rating', $taxonomy.'_'$term_id);
        }
        usort($terms, 'my_sort_function');
    }