Adding a class to the body_class function

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