3

I have created a radio button field with ACF so that admin can specify a colour. E.g:

  • blue : Blue
  • pink : Pink

I'd like this to be output as a class via <body <?php body_class(); ?> in header.php. Is this possible?

I'm currently outputting the class in header.php like so:

<div id="page" class="site <?php the_field('package_colour',$post->ID); ?>">
4

Hook into the body_class filter and add your field there. It might be better to get the ID from get_queried_object_id() instead of get_the_ID().

add_filter( 'body_class', 'wpse_20160118__body_class' );

function wpse_20160118__body_class( $classes ) {

    if ( $package_colour = get_field( 'package_colour', get_queried_object_id() ) ) {

        $package_colour  = esc_attr( trim( $package_colour ) );

        $classes[]       = $package_colour;
    }

    return $classes;
}
  • 1
    the_field functions output the value, not return. So get_field() is better. – Kolya Korobochkin Jan 18 '16 at 11:55
  • I've added this to functions.php and here's what I'm seeing via the inspector: <body blueclass="single single-products postid-136"> – Sam Jan 18 '16 at 11:55
  • 1
    Thanks @KolyaKorobochkin, using get_field() fixed the issue :) – Sam Jan 18 '16 at 11:56
  • 1
    get_the_ID() had produced problems for me and wasn’t reliable, your version is foolproof and works just well. – physalis Jan 26 '16 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.