Custom Sort for get_terms

When using get_terms to return term objects from a taxonomy, there is no built-in way to set a custom order, as you can with post object menu order, for instance. So the work around is to create a custom field for the taxonomy, use get_terms to pull the term objects, then loop through the generated array and create a new array with your custom field as the key for each item in the array…then sort that array. So for example:

//get all 'category' terms
$cats = get_terms( 'category' );

//set new empty array
$cat_array = array();

//loop through all the terms
foreach ($cats as $cat) {
     //set a variable for the custom field "sort_order" (the following assumes the use of ACF...if not, you'll need to use the more traditional way of getting a custom field)
     $sort_order = get_field( 'sort_order', $cat );
     //push the object into the new array with its 'sort_order' as the key
     $cat_array[$sort_order] = $cat;

//sort the new array
ksort( $cat_array, SORT_NUMERIC );

//loop through new array to output whatever it is you need to for the taxonomy terms in your custom order
foreach($cat_array as $cat_item){
     echo $cat_item->name;