I recently answered a thread in the WordPress support forums where someone was wondering how they could set up a tags page where their tags would be grouped by first letter. I posted the solution there as well as here. Hope someone finds the useful.

How it Works

Just copy the code below into a blank file and save it as “t-tags-alphabetical.php” in your current themes directory (I prefix all my page templates with “t-” – it makes it easier to find them). You will then need to log into WordPress, create a new page and apply the “Tags” template to it. You may also need to change the html under “OUTPUT” to match your theme. Please don’t change anything under “PROCESS” unless it makes sense to you :)

/*
Template Name: Alphabetical Tags
*/

/* PROCESS
================================================= */
	$list = '';
	$tags = get_terms( 'post_tag' );
	$groups = array();
	if( $tags && is_array( $tags ) ) {
		foreach( $tags as $tag ) {
			$first_letter = strtoupper( trim( $tag->name[0] ) );
			$groups[ $first_letter ][] = $tag;
		}
		if( !empty( $groups ) ) {
			foreach( $groups as $letter => $tags ) {
				$list .= "\n\t" . '<h2>' . apply_filters( 'the_title', $letter ) . '</h2>';
				$list .= "\n\t" . '<ul>';
				foreach( $tags as $tag ) {
					$url = attribute_escape( get_tag_link( $tag->term_id ) );
					$count = intval( $tag->count );
					$name = apply_filters( 'the_title', $tag->name );
					$list .= "\n\t\t" . '<li><a href="' . $url . '">' . $name . '</a> (' . $count . ')</li>';
					}
				$list .= "\n\t" . '</li>';
			}
		}
	}else $list .= "\n\t" . '<p>Sorry, but no tags were found</p>';

	/* OUTPUT
	============================= */
	get_header();
	?>
	<div id="container">
	<div id="main">
	<?php print $list; ?>
	</div>
	</div><!-- end main -->
	<?php
	get_sidebar();
	get_footer();
	?>

2 Responses to “Alphabetical Tags”

  1. [...] I’m looking has to be suitable for &#116&#101&#99hnology, and all things related to computers. Al&#112&#101&#104tical Tags – WordPress Page Template – mfields.org 07/11/2009 &#73&#32&#114ecently answered a thread in the WordPress [...]

  2. Rod Lawton says:

    Thanks for the code, Michael, which I found on the Wordpress forums. It’s exactly what I need, except that the titles (A, B, C, D etc) are indented progressively to the right on my page, and I my coding skills aren’t good enough to figure out why. Any chance you could help when you’ve got the time? Thanks.

Leave a Reply

You may use the following html: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>