Add a body class to a post with custom fields

Many times we want to add a specific class to the “body”, of a post.
With this method, you can do it easily using the power of the custom fields.

  1. Add this code to your functions.php and remember that your custom field name is “custom_body_css”
function add_new_class($classes) {
	if(get_post_meta(get_the_ID(), 'custom_body_css', true) && is_single())
		$classes[] = get_post_meta(get_the_ID(), 'custom_body_css', true);
	return $classes;
}

add_filter('body_class','add_new_class');

2. Add to your post a new custom field with Name “custom_body_css” on the left and value “my-class” on the right

That’s is, when you will refresh that post you will see the new class inside the <body> tag.

To extend this function, that is from this page:
https://webhostinghero.org/add-a-custom-body-class-in-wordpress/
and use it for a Custom Post Type, you must install the plugin Advanced Custom Fields.
Like this, you will be able to create a Custom Field for that specific CPT and add your class.
It will work with the above functions.php snippet without issues.

Scroll to Top