Add an A-Z menu at the top of A-Z listing code

I’ve done something similar before, for a glossary page. My code is below. Hopefully you can extrapolate from this. Note that I’;m using WP_Query not query_posts, as this is best practice.

<?php
    $args = array(
        'post_type' => 'my_glossary_term',
        'orderby' => 'title',
        'order' => 'ASC',
        'posts_per_page' => -1
    );

    $query = new WP_Query( $args );

    $dl="";
    $glossary_letter="";
    $active_letters = array( );

    while ( $query->have_posts() ) {
        $query->next_post();
        $term_letter = strtoupper( substr( $query->post->post_title, 0, 1 ) );
        if ( $glossary_letter != $term_letter ) {
            $dl .= (count( $active_letters ) ? '</dl>' : '') . '<li id="' . $term_letter . '"><span class="subheading">' . $term_letter . '</span><dl>';
            $glossary_letter = $term_letter;
            $active_letters[] = $term_letter;
        }
        $dl .= '<dt>' . $query->post->post_title . '</dt>';
        $dl .= '<dd>' . $query->post->post_content . '</dd>';
    }
    $dl .= '</dl></li>';

    $ul="<ul class="letters">";
    foreach ( array( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ) as $letter ) {
        $ul .= '<li>' . (in_array( $letter, $active_letters ) ? '<a href="#' . $letter . '">' . $letter . '</a>' : $letter) . '</li>';
    }
    $ul .= '</ul>';

    echo '<div id="glossary">' . $ul . '<ul class="definitions">' . $dl . '</ul></div>';
    ?>

Leave a Comment