I would like to add css classes to the body, based on the values of a custom field. The type of the field is multiple checkboxes.
This way I could quickly apply custom styles from the post editing screen, rather than maintaining long custom css with post-IDs. In the past, I did it with custom meta taxonomies but I want to avoid useless archive pages.
I have found this:
add_filter( 'body_class','my_body_classes' );
function my_body_classes( $classes ) {
global $post;
$classes[] = get_post_meta($post->ID, 'wpcf-my-custom-field', true);
return $classes;
}
It works fine when the field is a single checkbox. But with multiple checkboxes field, it will only add "Array" class. I have tried a few things but they either break the site or don't work. I suspect foreach would be required, but I am not able to do it myself. Perhaps you could help me out?
Thank you Minesh, that was very helpful. At first, it didn't work as expected but I made some modifications and as far as I can tell, it works now. It should be $classes[] or otherwise it will remove some of the existing classes.
I also expanded it to archives and term fields. If anyone needs it, here is what I've come up with: