Support

Account

Home Forums General Issues Give body a class based on true/false checkbox

Solved

Give body a class based on true/false checkbox

  • Hi there,

    since the net tells me I am not the only one interested in this I decided to ask/discuss here openly instead of opening a support ticket.

    I want something simple: Have a true/false checkbox on the edit screen of pages (or posts) that, when checked, adds a certain class to the body (in my case, for having less spacing around images than on ‘normal’ pages).

    So far I found the following to normally achieve my desired goal which is to be added to the functions.php:

    add_filter('body_class','acf_body_class');
    
    function acf_body_class( $classes ) {
    
    if ( get_post_meta( get_the_ID(), '_narrow_images', true ) ) {
    $classes[] = 'narrow-images'; /* Class to be added to body */
    }
    // return the $classes array
    return $classes;
    
    }

    while the custom field name (in the ACF options) is ‘narrow_images’. It works more or less good, only that some pages get the class which have no checkbox checked. There are no other conflicting custom fields, nor do any child or parent pages of these falsely class-i-fied pages have the checkbox activated.

    Is there, from your knowledge, anything wrong with the approach above? Does anybody have an idea of what could possibly interfere here?

    Thanks in advance 😉

    physalis

  • get_the_ID() can only be used inside the loop, see the WP Codex

    Using this function for the <body> tag would usually be outside the loop, so there is no telling what value is actually being returned.

    When you’re assigning classes you’ll need to get the post id using some other method.

    I’d probably use is_single() and/or possibly get_queried_object()

  • Ah, sorry for not getting back, I kind of forgot about this thread later, but your hint helped a lot, @Hube2. It could be solved, even without hitting the functions.php, by just using the field inside the loop, and that’s what I actually did then. Thank you so much!

  • This reply has been marked as private.
  • For me, I had a dropdown selection for some page options and needed to add a body class for each selection for styling.

    add_filter('body_class', 'add_acf_body_class');
    function add_acf_body_class($class) {
        $field = get_field_object('page_width', get_queried_object_id());
        $value = $field['value'];
        $label = str_replace( '_', '-', $value ); //Change _ to -
        $class[] = $label;
    
        return $class;
    }
Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Give body a class based on true/false checkbox’ is closed to new replies.