I currently categorize posts under a few main (Parent) categories and then specific (Child) categories per post like so:
- Human Resources
I’ve been looking (although I’ve only been looking for about a week) for a way to list unique categories per post. The default
the_category() template tag lists all categories a post falls under, allowing the user to specify the separator and the parent/child relationship, but I didn’t want the redundant Parent and Child link(s) listed.
So if a post is categorized as Code→PHP, the
the_category() template tag will return a list with links to the Code Category (parent) and PHP Category (child). Since “PHP” sits within “Code”, listing both is redundant for my purposes. Instead, I wanted just “PHP” to appear.
In my never‐ending quest to make script as user‐friendly as possible, I also wanted a link to the Parent Category to appear if a Child Category wasn’t selected when creating the post, and vice-versa; forgetting to select a Parent Category (which in my opinion, should automatically happen when selecting a Child Category — hint, hint WP devs).
The result is my first plugin written for WordPress. It’s pretty straight‐forward; It generates a HTML string of the categories associated with the current post. The name of each category will be linked to the relevant category page. If there is a redundant parent/child category pair, it returns a string of just the child categories. If there are no child categories it returns a string of parent categories.
- Download the “mish_wp_unique_cats.txt” file.
- Change the file extension to “php”
- Upload file to your plugin directory:
- Activate the plugin through your Admin Dashboard.
The plugin accepts 2 parameters; the separator and the ID of the post to use. If you set the post ID, you have to set the separator first, even if you want to use the default separator. See examples below.
The default usage is to separate the links with a comma and a space (“, ”) and to pull category links for the current post.
To call within your template, copy and paste the following code wherever you’d like it to appear (typically within the post‐meta paragraph).
Using the default.
<?php mish_wp_list_unique_categories(); ?>
Using a custom separator.
<?php mish_wp_list_unique_categories(' | '); ?>
Using a custom post ID.
<?php mish_wp_list_unique_categories('', 29); ?>
I hope this comes in handy for someone when developing a theme or just for learning purposes. It was designed specifically to handle the categorization used on this site, but it can be expanded to handle more parameters and fundamentally it could be used in other applications.