Skip to content

Instantly share code, notes, and snippets.

@srikat
Last active July 3, 2024 09:47
Show Gist options
  • Save srikat/064c507dc83b2dce680e02165069b605 to your computer and use it in GitHub Desktop.
Save srikat/064c507dc83b2dce680e02165069b605 to your computer and use it in GitHub Desktop.
Alphabetical terms of a taxonomy
<?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