# A–Z Index Shortcode for Glossaries and Directories

> Adds an [az_index type="glossary_term"] shortcode that lists every item of a post type grouped by first letter, with a jump-to-letter bar.

- Type: PHP
- Runs: Run everywhere
- Category: [Custom Post Types & Fields](https://wpide.com/library/category/post-types/)
- Tags: glossary, shortcode, directory
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/az-index-shortcode/

## Code

```php
add_shortcode( 'az_index', function ( $atts ) {
    $atts = shortcode_atts( array( 'type' => 'glossary_term' ), $atts, 'az_index' );
    $type = sanitize_key( $atts['type'] );
    $obj  = get_post_type_object( $type );

    if ( ! $obj || ! $obj->public ) {
        return '';
    }

    $key  = 'wpide_az_' . $type . '_' . get_option( 'wpide_az_ver_' . $type, '1' );
    $html = get_transient( $key );

    if ( false !== $html ) {
        return $html;
    }

    $ids    = get_posts( array( 'post_type' => $type, 'posts_per_page' => 1000, 'orderby' => 'title', 'order' => 'ASC', 'fields' => 'ids', 'no_found_rows' => true ) );
    $groups = array();

    foreach ( $ids as $id ) {
        $title  = get_the_title( $id );
        $letter = strtoupper( substr( remove_accents( $title ), 0, 1 ) );
        $letter = preg_match( '/^[A-Z]$/', $letter ) ? $letter : '#';
        $groups[ $letter ][] = '<li><a href="' . esc_url( get_permalink( $id ) ) . '">' . esc_html( $title ) . '</a></li>';
    }

    ksort( $groups );
    $nav  = '';
    $body = '';

    foreach ( $groups as $letter => $items ) {
        $anchor = 'az-' . ( '#' === $letter ? 'other' : strtolower( $letter ) );
        $nav   .= '<a href="#' . esc_attr( $anchor ) . '" style="padding:.25em .5em">' . esc_html( $letter ) . '</a>';
        $body  .= '<section id="' . esc_attr( $anchor ) . '"><h2>' . esc_html( $letter ) . '</h2><ul>' . implode( '', $items ) . '</ul></section>';
    }

    $html = $groups ? '<nav class="az-index-nav" aria-label="Jump to letter" style="display:flex;flex-wrap:wrap;gap:.25em">' . $nav . '</nav><div class="az-index">' . $body . '</div>' : '';
    set_transient( $key, $html, DAY_IN_SECONDS );

    return $html;
} );

add_action( 'clean_post_cache', function ( $post_id, $post ) {
    if ( $post && ! wp_is_post_revision( $post ) ) {
        update_option( 'wpide_az_ver_' . $post->post_type, (string) microtime( true ), false );
    }
}, 10, 2 );
```

## Notes

Works with any public post type, up to 1,000 items. The list is cached and refreshed when that post type changes.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "A–Z Index Shortcode for Glossaries and Directories" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
