I often find myself in need to style really particular items, articles or posts on site or a blog. There is a lot of options really, like using
class-name-ID;?> but I wanted to find a way to be able to predict the class selector name and write readable names in stylesheet for future references.
In order to achieve this behavior we will use the very same function that sanitizes the post title to use as WordPress slug:
sanitize_title() at WordPress codex
Pros and cons
Now there are pros and cons for this (there always is, isn’t it?), I’ll start with cons:
- The class selector may become very long (depends on post title)
- Class selector may conflict with others, predefined selectors if you not careful (again, depends on post title)
- Sometimes post title may change while if using post ID it will stay the same.
- Class selector predictable almost all the time
- Great flexibility in design
- Readable and understandable CSS selector in your stylesheet
The template code
Place in the template loop (pay attention to line #5 – this is where the class applied).
So if my post is titled “How to cook an omelet”, the CSS to style this post’s background color will be:
It really depends of what you prefer: in my opinion readable selector is much better option, especially when you have a bunch of hand picked posts to style.