How to add attributes to tag when template cannot be directly modified


This is similar to How to add data- attribute to <body> tag but different in that I am n ow searching for a solution that does not require modifications to the template file.

I have a requirement to add an attribute to the <body> tags in set of pages for which I cannot modify the template php file. For most of them, there is a theme-specific hook I’m using which is working fine. There are others that do not contain that hook. for these, I am able to achieve what I’m going for by essentially rewriting the final markup… with the attribute inserted – code used came from kfriend’s answer at

So I have these 2 approaches:

add_filter('theme_specific_hook', 'main_way');


add_filter('final_output', 'alternate_way');

The end result of each is

<body data-my-attr="MY VALUE" class="all-of the required-classes" ...>

which satisfies my requirement. The problem here is that I don’t have a way to tell WP when NOT to run the 2nd, less ideal filter.

I don’t know if this is an unnecessary and/or overly complicated workaround, but more importantly, I don’t even know if trying to conditionally take 1 of these 2 approaches is the most efficient way to go.

Does anyone have any input on this approach as far as best practices and or feasibility are concerned? Any other suggestions for ways to insert this attribute/value into the <body> tag of these pages regardless of their template?

, , Daveh0 5 months 0 Answers 65 views 0

Leave an answer