Adding a class to the body_class function

Basically I’ve applied this way to show certain colors on pages like search.php or a list on home.
What it does is it reads a variable that gets a field from WP, if that field is equal to a certain number then it adds a class name which in CSS has a color
Now the field on a single page is there, though whenever I add the ‘if system’ that I applied on the other pages it doesn’t add the class in the body on header.php. Now this works correctly on other pages(Not globally but individually) but not here for some reason.

On the header.php:

<?php
    //Body class
    if($mem_id == 1)          { $class="color1";    }
    if($mem_id == 2)          { $class="color2";    }         
    if($mem_id == 3)          { $class="color3";    }
    if($mem_id == 4)          { $class="color4";    }
    if($mem_id == 5)          { $class="color5";    }
    if($mem_id == 6)          { $class="color6";    }
    if($mem_id == 7)          { $class="color7";    }
    if($mem_id == 8)          { $class="color8";    }
    if($mem_id == 9)          { $class="color9";    }
?>
<body <?php body_class($class); ?>>

In other pages:
$mem_id = get_field('memtype_id');

2 Answers
2

Actually you just need a callback for the body_class filter. Then simply check what correlation you got between your meta data and the actual value: If it is a 1:1 correlation, you can just add the result of get_field() as new body class. Example: array( get_field( 'mem_id' ) ) if the mem_id meta value would be color3 for e.g. If not, then you can add it as a sprintf() argument and build your class like in the example below. Keep in mind to check if you actually got a value and if not, set a default.

add_filter( 'body_class', function ( $wp, $extra )
{
    return array_merge( $wp, (array) $extra, array(
        sprintf(
            'color%s',
            "" !== get_field( 'membertype_id' )
                ? get_field( 'membertype_id' )
                : "1" // default
        ),
        # additional declarations here
    ) );
}, 20, 2 );

This is just an example and you surely can be much more sophisticated in crafting a solution. Just try to not bind it too hard to the actual value or field name as such dependencies can quickly become a maintenance nightmare.

Also keep in mind that the only reason I used get_field() from the “AdvancedCustomFields” plugin as this was the tag originally added to the question. In real WordPress this would be get_post_meta() or get_post_custom() or similar (depending on what you exactly are retrieving).

Leave a Comment