2 min read
WordPress plugin: Add Categories to Menu
Using WordPress as a CMS? This little plugin gives your Blog menu link a submenu of all your blog categories.
If you're using WordPress as a CMS, you may have set up static pages for both a front page (e.g. "Home") and a page to list your latest blog posts (e.g. "Blog").
I did that today for a client site and immediately realized that in the site's main menu the Blog link would look a lot better if it had a submenu containing all the blog categories. (I didn't want nor did I need a completely separate category menu.) So I threw together this little bit of code that takes care of just that:
<?php
if ( !function_exists('add_blog_cats_to_menu') ) {
function add_blog_cats_to_menu($str) {
$cats = wp_list_categories('title_li=&echo=0');
$title = get_the_title(get_option('page_for_posts'));
return str_replace("title=\"$title\">$title</a>", "title=\"$title\">$title</a><ul>$cats</ul>", $str);
}
add_filter('wp_list_pages', 'add_blog_cats_to_menu', 1);
}
?>
For you programmers out there, this is just a slightly intelligent way to inject the output of wp_list_categories() into the output of wp_list_pages(), at the right place.
If looking at code scares you I've turned it into a plugin. Go to the Admin > Plugins > Add New page in your WordPress installation and search for "add categories to menu", or download it here (give that file a .php extension instead of .txt and upload it).
As soon as I have a live site sporting this plugin, I'll update this post with a link, so you can see a live demo.
I'm likely to update this shortly with a configuration page so you can specify categories to exclude, and so forth. Comment below if you urgently need that.
Updates
- 14 Dec. 2009 - As per Peter's comment below, I've used the echo parameter to avoid output buffering. Silly me! Simpler now.


