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.

Need help implementing a tutorial in your site or want to hire me for custom work?

HIRE ME

Find the article helpful and wish to donate?

DONATE

Comments

For adding code blocks wrap the code in three backticks. Markdown should work.
Provide a URL of your site/webpage if something is not working.
magnifiercross
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
%d bloggers like this: