Are you looking for a way to display a list of only subcategories? While there’s probably a plugin for this, we have created a quick code snippet that you can use to list all subcategories in WordPress.
Instructions:
All you have to do is add this code to your theme’s index.php file:
$echo = '<ul>' . "\n"; $childcats = get_categories('child_of=' . $cat . '&hide_empty=1'); foreach ($childcats as $childcat) { if (1 == $childcat->category_parent) { $echo .= "\t" . '<li><a href="' . get_category_link($childcat->cat_ID).'" title="' . $childcat->category_description . '">'; $echo .= $childcat->cat_name . '</a>'; $echo .= '</li>' . "\n"; } } $echo .= '</ul>' . "\n"; echo $echo;
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 12 best WordPress plugins for bloggers and how to create optin forms in WordPress.
I am so good at messing out so here is a few questions/comments:
Let’s say I have a main CAt called CARS and 3 sub-cats:
1)Sports Cars
2)Economic Cars
3)4 x 4
As we know now, if I have posts in cat #1 +2 +3, they will all show up under CARS – that is the standard in WP.
Now with this code, if user click CAR he will get only the 3 sub cats WITHOUT any posts at all?
Is this correct?
Second question:
Where do I add this code?
Thanks
Roger
[…] This post was mentioned on Twitter by Y Combinator Newest!, HN Firehose. HN Firehose said: WordPress display list of only subcategories: http://bit.ly/geanqN […]