Add a body class based on the value of a custom field / post meta

This morning I needed to add a body class to a page only if a meta value stored in the posts meta data was a certain value. It’s easy enough to do with the body_class filter and a couple of checks.

First, let’s see a basic example. To add a body class when the current post’s custom field value exists, do this:

Easy enough. But for my example, I wanted to only add the body class if the meta had a certain value, and I only wanted to add for pages, and I wanted to add the body class if either the current page or the current page’s parent had the meta value.

This is the first time I can remember where I checked for meta data when using the body_class filter, rather than just traditional conditionals, so I thought I’d share.

7 thoughts on “Add a body class based on the value of a custom field / post meta

  1. Great man. I wish more people utilized the body_class() function for styling different pages. I find it particularly useful for conditional browser styling.

    1. Yeah, I like it for these kind of conditions. Hybrid Core actually has the ability to have complete stylesheets on a per-post/page basis if you really want to get crazy. But for your average “I need to do this on these pages” scenario, these are great.

      In my case it’s subnav logic that affected the padding on a main content area wrapper, but I only wanted that extra space when my subnav (which is controlled by check metabox) was active : )

      Thanks for chiming in!

  2. Is there a way to take this and inject the value of the custom field as the class name?

    Example, if the page custom field is PM then the body class would be “body class=”pm” “

Leave a Reply