The WordPress function the_category doesn’t offer an exclude parameter. This does:
function exclude_post_categories($excl='', $spacer=' ') {
$categories = get_the_category(get_the_ID());
if (!empty($categories)) {
$exclude = $excl;
$exclude = explode(",", $exclude);
$thecount = count(get_the_category()) - count($exclude);
foreach ($categories as $cat) {
$html = '';
if (!in_array($cat->cat_ID, $exclude)) {
$html .= '<a href="' . get_category_link($cat->cat_ID) . '" ';
$html .= 'title="' . $cat->cat_name . '">' . $cat->cat_name . '</a>';
if ($thecount > 0) {
$html .= $spacer;
}
$thecount--;
echo $html;
}
}
}
}
Plus as long as you have that, you can alter the output however you want which is nice.
Usage is like:
<?php exclude_post_categories("4"); ?>
Which would list all categories excluding the one with the ID of 4.
Ey Up!
I use a very similar function.
Goes a little something like this…
The replacing > and < and the quotes have messed up the function slightly but you get the idea.
I think it uses slightly simpler way of adding the spacers and also allowed specifying an id of another post.
Maybe it will be of use…
Maybe not :)
There is a problem with this script. Let’s say I have 100 categories on the site… and I exclude 50 categories using the function above. What happens if there are only 5 categories in a post?
Well, the count would be 5-50 = -45. This messes up the “spacer”.
Thanks!
You could also use
the_category
filter orget_the_categories
filter like this:If you don’t want a comma after your last item, then use
if ($thecount > 1) {
instead of
if ($thecount > 0) {
Thanks for this great tutorial. It has helped me immensely. I was also wondering how to create nested (multilevel) categories. I’ve found this tutorial but not sure if it’s the best way to do so:
https://www.templatemonster.com/help/how-to-create-nested-multi-level-categories.html
What’s your opinion?