php - Indexed all categories of woocommerce according to alphabet

I need to get all the categories in indexed form according to the alphabet. I'm attaching picture output image of that i need. . is there someone that can help me out? Advance Thanks

Answer

Solution:

Try this:

/**
* This code should be added to functions.php of your theme
**/
add_filter('init', 'custom_default_catalog_orderby');

function custom_default_catalog_orderby() {
    $result = array();
    $categories = get_categories( array(
        'hide_empty' => 0,
        'orderby'    => 'name',
        'order'      => 'ASC'
    ) );
    // Store all category alphabet wise in $result array
    foreach( $categories as $cat ) {
        $first_char = mb_substr($cat->name, 0, 1);
        $result[$first_char][] = $cat;
    }
    // Print all categories alphabetically
    foreach($result as $alphabet => $c ) {
        echo "<h3>". ucfirst($alphabet) . "</h3>";
        // You can change HTML structure accordingly and manage like echo or return
        foreach($c as $category ) {
            $category_link = sprintf( 
                '<a href="%1$s" alt="%2$s">%3$s</a>',
                esc_url( get_category_link( $category->term_id ) ),
                esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
                esc_html( $category->name )
            );
            
            echo '<p>' . sprintf( esc_html__( '%s', 'textdomain' ), $category_link ) . '( '
                . sprintf( esc_html__( 'Post Count: %s', 'textdomain' ), $category->count ) . ')</p>';
        } 
    }
}

enter image description here

You can change action and HTML structure accordingly.

Source