frederik's blog

Music (5) Projects (2) Snippets (8) Technology (5) Thoughts (9)

Speak×

Creating WordPress menus from categories

!
/ (last edited)

I like to keep things simple.

For my new blog I wanted a menu at the top consisting of all the categories with posts in them. Additionally, I wanted to show the number of posts in every category.

It’s really straightforward to make this work. I put the following snippet inside of the header.php of my WordPress installation.

<?php
$base_url = "https://frjk.de/blog/category/";
$categories = get_categories('exclude=&title_li=');
foreach ($categories as $cat) {
    echo "<a href=\"".$base_url.$cat->category_nicename."\">".$cat->cat_name."</a> <span class=\"frjk-cat-counter\">(".$cat->category_count.")</span> ";
}
?>

Extended styling could be done by adding stuff to the <span> tag. I have a class ready for that in the code above but I don’t use it right now.

I’m happy with the minimalistic result.