Alphabetically ordered category list

I’m trying to achieve something like this:

A:

Parent Category Starting with A

  • Child Category
  • Child Category
  • Child Category

Another Parent Category Starting with A

  • Child Category

B:

Parent Category Starting with B

  • Child Category
  • Child Category
  • Child Category

…etc

I’m having trouble finding a plugin that does this and the ones I’ve found aren’t very good. Nor am I able to code it myself as I only have limited PHP knowledge.

I did however come across this snippet:

$list="";
$cats = get_terms('category');
$groups = array();
if( $cats && is_array( $cats ) ) {
    foreach( $cats as $cat ) {
        $first_letter = strtoupper( $cat->name[0] );
        $groups[ $first_letter ][] = $cat;
    }
        if( !empty( $groups ) ) {
            {
            $index_row .='<ul>';

                foreach ($groups as $letter => $cats) {
                    $index_row .= '<li><h4><a href="#' . $letter . '" title="' . $letter . '">' . apply_filters( 'the_title', $letter ) . '</a></h4></li>';
                    }

            $index_row .='</ul>';
            } //Index Row End 

            foreach( $groups as $letter => $cats ) 
            {
                $list .= '<div class="asset-cata clearfix">' . "\n";
                $list .= '<div class="letter">' . "\n";
                $list .= '<h1>' . apply_filters( 'the_title', $letter ) . '</h1>' . "\n"; // The Letters On Their Own
                $list .= '</div>' . "\n";

                $list .= '<div class="list-items">' . "\n";
                $list .= '<ul>' . "\n";

                    foreach( $cats as $cat ) 
                    {

                        $url = attribute_escape( get_category_link( $cat->term_id ) );
                        $name = apply_filters( 'the_title', $cat->name );

                        $list .= '<li class="item">' . "\n";
                        $list .= '<a title="' . $name . '" href="' . $url . '">' . $name . "\n";


                                    $list .= '<span class="number">'. $cat->count .'</span> ' . "\n";

                        $list .= '</a>' . "\n";
                        $list .= '</li>' . "\n";
                    } 

                $list .= '</ul>';
                $list .= '</div>';
                $list .= '</div>';
            }   

    } // GRoups End
} else 
$list .= '<p>Sorry, but no cats were found</p>';

`

Which does partly do what I’d like, but it doesn’t put child category with their parents, which is what I want to achieve

1 Answer
1

Found the solution. Simply add

$args = array(
    'parent'  => '0',
); 

at the top, and change

$cats = get_terms('category');

to

$cats = get_terms('category', $args);

There are more values, see https://codex.wordpress.org/Function_Reference/get_terms

Leave a Comment