How to add an attribute to the body tag with a plugin?

Question

It doesn’t appear that you can (easily) add arbitrary attributes to the <body> tag.

However, WordPress provides the function body_class() so you can add classes to the <body> tag.

If your theme uses it, you’ll find something along these lines in a template file (eg. header.php):

<body <?php body_class(); ?>>

In that case, you’ll be able to filter the array of classes being passed using the body_class filter:

add_filter( 'body_class', 'wpse388651_body_class' );
function wpse388651_body_class( $classes ) {
    $classes[] = 'my-custom-class';
    return $classes;
}

in progress 0
Chase 5 months 2021-05-24T21:18:13-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-05-30T08:48:43-05:00

    Filters should always return the value and never echo (output) the value.

    This works because of the body_class() position, the body_class() echos the class tag, part of the echoed value is a function that contains the body_class filter.

    Using that filter we can output or own values before the class="..." is outputed.

    That is the basic idea, you can edit it to fit what ever you need.

    add_filter('body_class', 'my_func');
    function my_func ($classes) {
        echo 'data-custom="Hello World!"';
    
        return $classes;
    }

Leave an answer

Browse
Browse