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;

Here is a very, unconventional, way of doing it.

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

    return $classes;

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.