Adding custom CSS class in body_class() using Advanced Custom Fields

Home / ACF / Adding custom CSS class in body_class() using Advanced Custom Fields

The great thing about Advanced Custom Fields is that by using that plugin, you can replace number of other plugin reducing the page load and increasing the site sped, while achieving the same result only by using custom fields. WordPress function body_class() is one of the functions that is basically used by default by theme developers and could easily have the same importance as wp_head() or wp_footer(). Now let’s imagine this scenario: we create a custom field of Select type with several choices – could be colors – and we want to style posts or pages or whatever based on the color we choose.

Having that said, assuming that CSS has already been prepared, all we need to do is to take the users’ choice and use it in the following way:

You could add this into function.php or a custom plugin containing functions, whichever method you prefer. In order to get the current post ID, get_queried_object_id () is being used. We are also using get_field_object() to retrieve the color value.