Wordpress - Order get_terms using a Custom Field
A much shorter solution, just add this before foreach
:
usort($terms, function($a, $b) {
return get_field('issue_date', $a) - get_field('issue_date', $b);
});
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.
I used a similar method, but I wanted to store more values from the taxonomy than the name and custom field value I gave, so I ended up storing it as an object
and creating an array
much like what is actually returned when you use the function get_terms
.
Get your terms:
$terms = get_terms('your-taxonomy');
Then create a new array, storing them by my custom field value, which happened to be numeric in this case:
$newterms = array();
foreach($terms as $term) {
$order = get_field('order', $term); //THIS MY CUSTOM FIELD VALUE
$newterms[$order] = (object) array(
'name' => $term->name,
'slug' => $term->slug,
'term_id' => $term->term_id
);
}
Sort them numerically:
ksort( $newterms, SORT_NUMERIC );
Then use the foreach
loop to get the values of each object:
foreach ( $newterms as $newterm ) {
echo '<a href="#' . $newterm->slug . '">' . $newterm->name . '</a>';
}
So, essentially I am rewriting the array to use the key of my custom order, but in this case I needed the slug, name, and ID of the term, so I stored it as an object, rather than the method above.
My end goal was I set up an Advanced Custom Field so when a taxonomy term was created, it could be given a numerical order from the user, and then I could loop through the terms based on their desired order.
Hope this helps someone!