Explanation of the body_class() WordPress function

The job of the built-in body_class() function in WordPress is to add all the necessary class names to the <body> element of each page or post. This is why you usually find this function called within the header.php file of a theme, as that file is loaded on every page or post.

It results in markup like:

<body class=”home blog logged-in”>

The classes it outputs change dynamically depending on what page is being viewed. For example, on the homepage you might see home, on a single post page single single-post, on a category archive archive category, and so on.

WordPress also adds classes based on the current user’s state, such as logged-in or admin-barwhen the WordPress toolbar is visible.

This is extremely useful for CSS targeting.

Using body_class() to add your own custom classes

You can also add your own custom classes by passing them as an argument — body_class( 'my-custom-class' ) — or by hooking into the body_class filter in your functions.php, giving you full control over what classes are appended without modifying the template directly.

1. Passing a class directly as an argument

In your theme’s header.php, where body_class() is called:

Example of passing a class directly as an argument.

You can also pass multiple classes as an array:

Example of passing multiple classes as an array.

This is quick but hardcoded — the class always appears regardless of context.

2. Hooking into the body_class filter

In your functions.php, you can conditionally add classes without touching the template:

Add a class to all pages:

Example of adding a hardcoded class to all pages.


Add a class conditionally:

Example of conditionally adding classes using the body_class filter.


The rendered HTML would look something like:

The rendered HTML of the previous example.


The filter approach is preferred in WordPress development because it keeps your logic in functions.php and your templates clean — you never need to touch header.php to control body classes.

Note: Omitting this function won't break your site visually, but you will lose a significant amount of styling and plugin flexibility, since many plugins and tools rely on specific body classes being present to function correctly.

Wrapping Up

Provided that your theme’s body element includes this function, it will automatically incorporate the respective to each page WordPress-generated CSS classes.

After that, you will also be able to add your own custom CSS classes to the body element. You can add these classes whenever you need them.

Although my blog doesn’t support comments, feel free to reply via email or X.