12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Mar 13, 2020

How to add custom body class(es) to Pages in WordPress

Sridhar Katakam

In the Oxygen Facebook group a user asks:

Hello Oxy helpers.

I’m trying to find a way to add a css class to the body tag.

I’ve got a hero bg image on each page, but some are light others are dark, so I want to change the logo accordingly. So I thought adding a “light” or “dark” to the body tag would then give me the function to change the logo via css.

Thanks for your help

This tutorial provides the steps to add a “Body Class” meta box for Pages using Advanced Custom Fields and add the text entered in this custom field to the classes list for body element on the front end using the body_class WordPress filter hook.

Step 1

Install and activate Advanced Custom Fields (free or Pro).

Add a new field group titled say, “Page Fields” having a body_class text-type field.

Set the field group to appear on Pages.

Step 2

Install and activate Code Snippets plugin.

Go to Snippets > Add New.

Title: Add body class to Pages

Code:

add_filter( 'body_class', 'custom_body_class' );
/**
 * Add custom field body class(es) to the body classes.
 *
 * It accepts values from a per-page custom field, and only outputs when viewing a singular static Page.
 *
 * @param array $classes Existing body classes.
 * @return array Amended body classes.
 */
function custom_body_class( array $classes ) {
	$new_class = is_page() ? get_post_meta( get_the_ID(), 'body_class', true ) : null;

	if ( $new_class ) {
		$classes[] = $new_class;
	}

	return $classes;
}

Set the snippet to run only on the front-end.

Save and activate.

Step 3

Edit the Page for which you wish to add a custom body class.

Enter your desired body class in the Body Class meta box.

To add multiple classes, separate them by classes. Ex.: dark has-sidebar.

Update the Page.

Reference

lib/structure/layout.php of Genesis.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right