Category Alphabet List Broken

ANSWER REVISITED

I have just done the same type of answer on SO and took another route that is way faster than my original answer. I thought it would be nice to revisit this answer and post my new approach for benefit of this site.

The name__like parameter of get_terms was changed in WordPress 3.7. It does not retrieve term names with a specified first letter anymore, but retrieves a term name if it has the specified letter any where in the name

Also, if you are going to try to run your code 26 times, you are going to have issues with page load times

Here is my approach and the test results

Test results: 1 query in 0.01074 seconds.

Test output: (Please note, my test site is in Afrikaans, all names is term names)

enter image description here

Here is the code that makes it happen

$terms = get_terms('pa_manufacturer');

if ( !empty( $terms ) && !is_wp_error( $terms ) ){    
$term_list = [];    
foreach ( $terms as $term ){
    $first_letter = strtoupper($term->name[0]);
    $term_list[$first_letter][] = $term;
}
unset($term);

echo '<ul class="my_term-archive">';

    foreach ( $term_list as $key=>$value ) {
        echo '<h2 class="term-letter">' . $key . '</h2>';

        foreach ( $value as $term ) {
            echo '<li><a href="' . get_term_link( $term ) . '" title="' . sprintf(__('View all post filed under %s', 'my_localization_domain'), $term->name) . '">' . $term->name . '</a></li>';
        }
    }

echo '</ul>';
}

HOW THE CODE WORKS

The best approach here is to get all the terms in one go to avoid unnecessary db hits. You can now pass the result from get_terms through a foreach loop.

Here you are going to resort your terms. First thing to do is to create a new array, $term_list, get the first letter of each term name, and then assign this letter as a key in the new array. The values for each key will hold an array of the term info

This new array will ten be used to display term names under each letter as you can see in the image above.

Leave a Comment