Rather than adding a lot of extra PHP code (not to mention the fact I wasn’t sure if it was even possible) to exclude this certain category I decided to use a CSS selector to accomplish the task.
The category that I wanted to exclude was named Feature. So by default, when you use the_category() within the WordPress Loop, the category(ies) is output in HTML as an anchor tag with a link to the category and a unique title attribute. This output is shown in Figure 1.
- <a href="http://website-address.com/category/feature/" title="View all posts in Feature" rel="category tag">Feature</a>
Using CSS selectors I am able to select HTML elements by various attributes, one of these being the title. So if I knew that each time the Feature category was displayed it was going to have that exact title, I could select it with CSS and give it a display value of none to make it disappear. The CSS used to accomplish this is shown in Figure 2.
- a[title="View all posts in Feature"]
- {
- display:none;
- }
That’s it! Now whenever the Feature category is output it is hidden by the CSS. Now of course this isn’t excluding it completely, if the style sheets are disabled or the source code viewed then the category will be visible. In most cases though, this is sufficient.
To avoid confusion (and unnecessary work!) if you are displaying a list of categories independent of the posts, such as in the sidebar, then you would use wp_list_categories or wp_dropdown_categories and the functionality to exclude certain categories is already included.
I had thought that I’d seen a parameter of one of the template tags which acted as a restrictor, but I can’t find it. There is what at least appears to be a trivial way to do this, with something like
will exclude all posts from the category with ID “3″. I think the CSS selector thing is elegant; but if it’s important that the solution work across user scenarios, this might work a little better.
Addendum: appears putting stuff inside code tags kinda broke stuff. The relevant pieces, to be placed inside the PHP brackets, is…
if (in_category(’3′)) continue;
Nice post David. I didn’t think about using the selector like that.
@ Daniel - That would exclude all posts within that category, but he wanted to excluded a certain category link from the categories associated with each post not remove the post completely from that specific WordPress loop.
Thanks, Will. Love your new design by the way, and congrats on the new baby!
Thanks David on the site and the baby! My site still needs some work but it will hopefully be looking even better soon.