WordPress Snippets at WPcustoms

List taxonomies by initial letter

Tired of tagclouds? Here is a pretty nice snippet for your next archive template. This code lists tags or custom taxonomies by letters in an unordered list. If you just want to list your post tags replace ‘CUSTOM-TAXONOMY’ with ‘post_tag’.


/**
 * Snippet Name: List taxonomies by initial letter
 * Snippet URL: https://wpcustoms.net/snippets/list-taxonomies-by-initial-letter/
 */
  $list = '';
$args = array(
  'hide_empty' => true,  // Set this to true to hide terms with no posts
);
$tags = get_terms('CUSTOM-TAXONOMY',$args);
$groups = array(  );

if( $tags && is_array( $tags ) ) {
  foreach( $tags as $tag ) {
    $first_letter = strtoupper( $tag->name[0] );
    $groups[ $first_letter ][] = $tag;
  }
  if( !empty( $groups ) ) {
    $index_line = '';
    foreach( $groups as $letter => $tags ) {
      $list .= '
'; } $list .= ''; } } else $list .= '

Sorry, but no tags were found

'; print ($index_line); print ($list);