In one of my WordPress projects I needed to theme some links in the header based on the post’s main category. The easiest way for me to quickly tackle this problem was to add the WordPress post category body class, then use some CSS rules to style the links.
If you ever find yourself in the same situation, you can use this script in your theme’s functions.php to quickly solve the problem.
WordPress post category body class
function add_category_name($classes = '') {
if(is_single()) {
$category = get_the_category();
$classes[] = 'category-'.$category[0]->slug;
}
return $classes;
}
add_filter('body_class','add_category_name');
Please let me know if this article helped you and share your thoughts in the comment section. If the code snippet helped you a lot, you can buy me a beer any time using the Beer button in the sidebar 🙂 Cheers!