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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.