I have a query which outputs a list of taxonomy tags, organised by FIRST NAME with an alphabetical heading, like so:
E
Elena Ferrante
H
Helen DeWitt
J
Joan Didion
Jonathan Franzen
K
Kazuo Ishiguro
M
Maggie Nelson
P
Plato
R
Rachel Cusk
Roberto Bolaño
S
Sheila Heti
etc.
How can I alphabetize this list of taxonomy tags by LAST NAME instead of FIRST NAME? So the result would be:
B
Roberto Bolaño
C
Rachel Cusk
D
Helen DeWitt
Joan Didion
F
Elena Ferrante
Jonathan Franzen
H
Sheila Heti
I
Kazuo Ishiguro
P
Plato
N
Maggie Nelson
etc.
Here is the query:
<?php
$list = '';
$groups = array();
$tags = get_terms('authors',$args);
if( $tags && is_array( $tags ) ) {
foreach( $tags as $tag ) {
$first_letter = strtoupper( $tag->name[0] );
$groups[ $first_letter ][] = $tag;
}
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
$list .= "<div class='titleLetter'>" . $letter . "</div><ul>";
foreach( $tags as $tag ) {
$list .= '<li><a href="/authors/'.$tag->slug.'">'.$tag->name.'</a></li>';
}
$list .= '<br></ul>';
}
$list .= '';
}
}
echo $list; ?>
If the given code works for First Name ordering. Then this one will work for orderby lastname.
<?php
$list = '';
$groups = array();
$tags = get_terms('authors',$args);
if( $tags && is_array( $tags ) ) {
$i=0;
foreach( $tags as $tag ) {
$lastname_arr=explode(' ', $tag->name);
$lastname=$lastname_arr[count($lastname_arr)-1];
$first_letter = strtoupper( $lastname[0] );
$groups[ $first_letter ][$lastname.'_'.$i] = $tag;
$i++;
}
foreach($groups as $key=>$group ){
ksort($groups[$key]);
}
ksort($groups);
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
$list .= "<div class='titleLetter'>" . $letter . "</div><ul>";
foreach( $tags as $tag ) {
$list .= '<li><a href="/authors/'.$tag->slug.'">'.$tag->name.'</a></li>';
}
$list .= '<br></ul>';
}
$list .= '';
}
}
echo $list;
?>
What i did here are: