Skip to content

WordPress Category List by Alphabet Code Without Plugin

WordPress Category List by Alphabet Code Without Plugin

In your functions.php, insert the code below. In the page or post or wherever you want, just use the shortcode [sorted_category_list] and the sorted category list will appear 🙂

add_shortcode('sorted_category_list', 'sorted_category_list_shortcode');

function sorted_category_list_shortcode() 
{
    $html = "";
    
    $categories = get_categories( array(
        'orderby' => 'name',
        'order'   => 'ASC',
        'include_last_update_time' => false,
    ) );
    

    if( empty($categories) ) {
        $html .= "<p>Category list is empty</p>";
    } else {
    
        // Sort categories 
        $sorted_categories = [];
        foreach( $categories as $category ) 
        {
            $category_name = $category->name;
            if( count($category_name) > 0 ) {
                $first_char = $category_name[0];
                $first_char = strtoupper($first_char);
                if( ctype_alnum($first_char) ) {  // if $first_char is alphanumeric
                    $sorted_categories[$first_char][] = $category;
                } else {
                    $sorted_categories['Others'][] = $category;
                }
            }
        }			
        
        foreach( $sorted_categories as $initial=>$categories ) 
        {
            $html .= "<p style='font-weight:bold;'>{$initial}</p>";
            $html .= "<ul>";
            foreach($categories as $category) 
            {
                $category_name = $category->name;
                $category_id = $category->term_id;
                if( $category_id > 0 ) {
                    $category_link = get_category_link($category_id);
                    $html .= "<li><a href='{$category_link}'>{$category_name}</a></li>"; 
                } else {
                    $html .= "<li>{$category_name}</li>";
                }				
            }
            $html .= "</ul>";	
        }

    }
    return $html;
}

 

Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.