Site logo

Archived topic

Adding wrapper class to content based on ACF field?

5 replies · Started by Espen on May 29, 2021

Viewing posts 1–6 of 6

Hi,

I'd like to have a checkbox in my post admin screen using ACF. When that is checked I'd like to add a class to the main content of the blog post. This is so that I can style the content slightly differently on a per post basis.

What is the best way in GP to add the necessary PHP to test for the condition and add a wrapper class? I know I could make a child theme single.php and put it there, but I thought perhaps there is a more elegant solution? :)

Thanks!

Best Regards,

Espen

Hi there,

is this for a Single Post content or in the Archives/Blog ?

Hi David,

This is for single post content.

-Espen

You can add a PHP Snippet like this:

add_filter( 'body_class', function( $classes ) {
    // Check if single post
    if ( is_single() ) {
        // get ACF field and load into $body_class var
        $body_class = get_field( 'your_custom_field' );
        // if True output body class
        if ( $body_class ) {
            $classes[] = 'my-special-class';
        }
    }

    return $classes;
} );

This will add a class to the <body> element of any post where the ACF field condition is met ... in my example it will add: my-special-class which you can use to target just those posts.... Change that to what you will.

This can be added to your child theme functions.php or using the code snippets plugin.

Note i used the body class instead of adding it the post element as this will give you wider scope for styling that post.

Thank you, David!

That worked perfectly!

Have a great weekend!

-Espen

Glad to be of help

This archived topic is closed to new replies.