Home Forums Front-end Issues Add body class based on ACF block choice


Add body class based on ACF block choice

    • jfarr

    • May 12, 2020 at 1:24 am

    I am trying to add a body class based on an ACF block value.

    My hero block has different layout choices. This is using the button_group field. The choices for the admin are:


    I would like to output the value of these choices as a body class. It would also be ideal to have the script inside the block php (hero.php). I’ve tried the following but I cannot seem to get it to output.

    function add_acf_body_class($class) {
    	$value = get_field('background_choice');
    	$class[] = $value;
    	return $class;
    add_filter('body_class', 'add_acf_body_class');
  • Hey @jfarr,

    I’ve just tested this, and whilst the function won’t work from within the include, it will work within your theme’s functions.php file.

    Move it there and you should get the result you seek.

    Cheers, Dan

  • The reason that this works in functions.php and does not work in the bock.php file is that the WP hook body_class runs before the template file is loaded. The filter must be added before the hook is run.

  • Good to know @hube2

    • jfarr

    • May 16, 2020 at 1:03 am

    I think what we’re missing is the ability to access the get_field() outside the blocks loop. I’m not sure how to do this.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.