Create an A-z List of Your Members

Problem

You have a growing community of website members, and want to list them on one page, sorted alphabetically by last name and grouped by first letter.

Solution

There are two tricks to this recipe:

  1. The first trick is to use Craft’s handy group filter to perform the heavy lift of the grouping.
  2. The second trick is that the group filter itself takes a string that can be further filtered, allowing us to use Twig’s first filter to group by just the first letter of each last name.
{% set membersGrouped = craft.users.limit(null).order('lastName') | group('lastName | first') %}

{% for letter, members in membersGrouped %}
    <h2>{{ letter | upper }}</h2>
    <ul>
        {% for member in members %}
            <li>{{ member.lastName }}, {{ member.firstName }}</li>
        {% endfor %}
    </ul>
{% endfor %}

Let’s start by breaking down the first line:

  1. We start by querying our users, limiting by null to grab everyone, and ordering by the built-in lastName field;
  2. Then we group the result by the first letter of the lastName field;
  3. This grouped result is then set to our membersGrouped variable.

When we get back membersGrouped, it’s an array where each key is a letter in the alphabet, and each value is another array of all users whose Last Name starts with that letter.

With that in mind, we start by looping through membersGrouped, iterating over keys and values, assigning our key to letter, and our array of users to members. This allows us to output each letter as an H2 heading, and then we perform another loop, running through each member.

Discussion

This solution is not limited to Members - and as illustrated doesn’t have to be limited to titles!

Having trouble with this recipe, or prefer a plugin to give you more power? Have a look at Glossary from Experience.