I have created an Authors taxonomy. Each author has a name and surname in the name field. Later on the taxonomy page, the list is displayed in alphabetical order.
<?php
$taxonomy = 'autorzy'; // <== Here define your custom taxonomy
$sorted = array(); // Initializing
// Get all terms alphabetically sorted
$terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'orderby' => 'name'
) );
// Loop through the array of WP_Term Objects
foreach( $terms as $term ) {
$term_name = $term->name;
$image = get_field('obrazek_wyrozniajacy', $term);
$term_link = get_term_link( $term, $taxonomy );
$first_letter = strtoupper($term_name[0]);
// Group terms by their first starting letter
if( ! empty($term_link) ) {
$sorted[$first_letter][] = '<li><a href="'.$term_link.'">' .'<img src="'.$image['url'].'" />'.$term_name.'</a></li>';
} else {
$sorted[$first_letter][] = '<li>'.$term_name.'</li>';
}
}
// Loop through grouped terms by letter to display them by letter
foreach( $sorted as $letter => $values ) {
echo '<div class="tax-by-letter" id="tax-letter-'.$letter.'">
<h3 class="tax-letter-'.$letter.'">'.$letter.'</h3>
<ul class="nav">' . implode('', $values) . '</ul>
</div>';
}
?>
The problem is that authors are sorted by first name, and I would like the sorting to be by last name. What do I need to improve?
2
Answers
I added this code to functions.php
Then in the php template I added
Unfortunately, nothing has changed and authors are still sorted by name.
You won’t be easily able to sort on a string partial in an efficient way, so I would suggest breaking
firstName
andlastName
apart when the post is saved, and storing them each within their own metadata field:Docs:
created_{$taxonomy}
https://developer.wordpress.org/reference/hooks/created_taxonomy/
update_term_meta()
https://developer.wordpress.org/reference/functions/update_term_meta/
taxonomy query params
https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
orderby with meta_value_num
https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters