Add Custom CSS To Articles Under Certain Categories
Latest update: May 10, 2022 | Reading time: 3 to 4 minutesThe problem: you need to apply a special style to the articles of a specific category. WordPress does not offer this option out of the box. It allows for customizing separate pages according to their page-id or to customize a category listing. It does not provide us with the option to apply custom style to a series of articles that belong to a category.
The solution: we need to create a new filter to the funtions.php (it exists in the theme’s folder under /wp-content) that will add a class with the category name to the body of the single article. For this, we’ll use a new function that will apply when a single post is loaded. Then, we can use the new class to apply any custom CSS to the posts of the category.
The workaround: First, copy and paste the following lines on /wp-content/function.php .
You can do that directly from WordPress (via Dashboard > Appearance > Theme Editor and selecting the appropriate file). However, we recommend using an FTP client like Filezilla (or the file explorer of the hosting panel) because PHP files are very sensitive and even a typo can break the site. Using external access allows for immediately correcting or restoring the contents of a file.
If you need to keep this code permanently on the site, use a child theme (add the code to the corresponding child theme’s file).
<?php function body_class_add_categories( $classes ) { if ( !is_single() ) return $classes; $post_categories = get_the_category(); foreach( $post_categories as $current_category ) { $classes[] = 'category-' . $current_category->slug; } return $classes; } add_filter( 'body_class', 'body_class_add_categories' ); ?>
Next, go anywhere on the site you can add custom CSS and add a new rule.
For example:
Hypothetically you have a category that is called “green-news” and you need to change the font colour of the paragraph text of all posts under the specific category to green. Add the following lines to the custom CSS field:
.category-green-news p { color: green; }
Note that, the name of the category can be different from the slug (which is the one you need to use on the CSS). To review the category slug go to Dashboard > Posts > Categories and check the corresponding column (or field, for each category separately). Last but not least, this might not work for other languages than English as the letters may contain additional characters that might not comply with PHP syntax.
VALID FOR ANY THEME