Often you need to add several classes to the body class besides the default classes. We can update the WordPress body class using a filter. In Roots Sage and most themes you have several ways to do this. You could add the filter, use __NAMES_SPACE__ magic constant and then add the function.

The value of __NAMESPACE__ is a string that contains the current namespace name. In global, un-namespaced code, it contains an empty string.

https://www.php.net/manual/en/language.namespaces.nsconstants.php

In that function you can use array_merge :

add_filter('body_class', __NAMESPACE__ . '\\body_class');

function body_class($classes) {
    return array_merge( $classes, array( 'bg-white text-gray-600 work-sans leading-normal text-base tracking-normal' ) );
}

Then you can do the same method but use an array , fill it and then return it:

add_filter('body_class', __NAMESPACE__ . '\\body_class');

function body_class($classes) {
    $classes[] = 'bg-white text-gray-600 work-sans leading-normal text-base tracking-normal';
    return $classes;
}

and the final way is to not use __NAMESPACE__ , return an array_merge of classes to add to the body class:

add_filter( 'body_class', function( $classes ) {
    return array_merge( $classes, array( 'bg-white text-gray-600 work-sans leading-normal text-base tracking-normal' ) );
});

__NAMESPACE__ was needed in Sage 8 but is no longer needed in Sage 10 and will also not be needed in most other themes.

So short and sweet version we tend to use is

/**
 * body_class filter
 * @link https://developer.wordpress.org/reference/functions/add_filter/
 * @link https://developer.wordpress.org/reference/hooks/body_class/
 */
add_filter( 'body_class', function( $classes ) {
    return array_merge( $classes, array( 'bg-white text-gray-600 work-sans leading-normal text-base tracking-normal' ) );
});

Leave a Reply

Your email address will not be published. Required fields are marked *