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

Is there any way to add an attribute to the body tag?

For example:

<body test-attribute>

Obviously this can be easily edited in the theme, but I’m trying to figure out how to add it with a plugin.

2 Answers
2

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;
}

Leave a Comment