Last active
July 3, 2024 09:47
-
-
Save srikat/064c507dc83b2dce680e02165069b605 to your computer and use it in GitHub Desktop.
Alphabetical terms of a taxonomy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$taxonomy = 'category'; // set your taxonomy here | |
$terms = get_terms( $taxonomy, [ | |
'hide_empty' => true, | |
'orderby' => 'name', | |
'order' => 'ASC', | |
] ); | |
$grouped_terms = []; | |
foreach ( $terms as $term ) { | |
$first_letter = strtoupper( $term->name[0] ); | |
if ( ! isset( $grouped_terms[ $first_letter ] ) ) { | |
$grouped_terms[ $first_letter ] = []; | |
} | |
$grouped_terms[ $first_letter ][] = $term; | |
} | |
$output = ''; | |
foreach ( $grouped_terms as $letter => $terms ) { | |
$output .= '<h2>' . $letter . '</h2>'; | |
$output .= '<ul>'; | |
foreach ( $terms as $term ) { | |
$output .= '<li><a href="' . esc_url( get_term_link( $term ) ) . '">' . $term->name . '</a></li>'; | |
} | |
$output .= '</ul>'; | |
} | |
echo $output; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment