I’m customizing a WordPress installation and was wondering what the best way to do this is. I want to customize each post completely depending on the category. Each post will be under only one category.
Leave a Reply
You must be logged in to post a comment.
for the css route, you can use the
post_class()
function to give you category dependant css classes.if you go beyond formatting, i.e. output different elements depending on the category, you could use the conditional tag
in_category()
in an ‘if-elseif-else’ structure.the category archives can be done with category templates.
There’re 2 functions that help you handle the classes in WP:
body_class()
andpost_class()
. When you usebody_class()
, you can style the post that in a certain category like this (in your CSS file):If you want total control, then a css solution is not enough. a more powerful solution is to create a sort of template hierarchy for single posts based on the category slug. Here is the general idea.
In single.php find out the categories connected to the post using get_the_category() – if as you say there will only ever be one category assigned, then just use the first value in the returned array. then once you have the cat object, get it’s slug. from there see if that filename exists in the theme folder that matches ‘single-‘ plus catslug and load it if it does. Otherwise continue using the regular single post loop. then you create post templates for specific categories and name them based on the category slug. ie. single-mycatslug.php.
here is some code:
I run this on a production site and it works great.
Add a custom class in your functions file to style all posts in a category the same as well as the category archive page.
And some sample CSS:
Here is how I would do it:
For example; PHP, that goes straight in the
functions.php
of your theme:And CSS, for the
style.css
file of your theme:Not that much savvy, as every time you create a new category, you have to add a new style selector in the CSS to style the posts with this new category.