Code & Snippets

How to Add a Custom Body Class Based on Category

By Daniel Ekay May 18, 2026 2 min read
Docs Code & Snippets How to Add a Custom Body Class Based on Category
Share:
Last updated:

WordPress automatically adds category-based body classes on archive pages (e.g. category-travel), but single post pages do not get a category body class by default. This means you cannot target posts by category with CSS unless you add it yourself.


The Snippet

Add this to your child theme’s functions.php:

Child theme folder structure showing style.css, functions.php and other child theme files
add_filter( 'body_class', function ( $classes ) {
    if ( is_single() ) {
        $categories = get_the_category();
        foreach ( $categories as $category ) {
            $classes[] = 'category-' . $category->slug;
        }
    }
    return $classes;
} );

This adds one body class per category the post belongs to, using the same format WordPress uses on archives: category-{slug}. A post in both “Travel” and “Food” categories gets both category-travel and category-food.


Using It with CSS

Once the class is in place, you can target it in Additional CSS or your child theme stylesheet. For example, to disable the drop cap on all posts in the “News” category:

Drop Cap Style setting in the Single Post Layout panel with Pretty selected
.category-news .aurora-dropcap::first-letter {
    font-size: inherit;
    float: none;
    font-weight: inherit;
    line-height: inherit;
    margin: 0;
    padding: 0;
}

Or to apply a different sidebar background on a specific category:

Aurora Colors panel showing header background, menu text, footer background, sidebar and site background color options
.category-recipes .site-sidebar {
    background-color: #fdf6ec;
}

Aurora’s Built-in Body Classes

Aurora already adds several body classes of its own, including vertical-header for vertical header layouts and dropcase-{style} when the drop cap is enabled. The category class above adds to these without conflict. See Aurora’s CSS Variables for other ways to customise specific elements.

Make your blog stand out

Enjoy the ease and flexibility of Aurora. Create stunning blog designs your readers will love, with live preview editing and effortless template mixing and matching enabled.

Get Aurora today for just $39

Get Aurora