0

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 https://stackoverflow.com/questions/772510/wordpress-filter-to-modify-final-html-output.

So I have these 2 approaches:

add_filter('theme_specific_hook', 'main_way');

and

add_filter('wp_footer', '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?

2
  • “ The problem here is that I don't have a way to tell WP when NOT to run the 2nd, less ideal filter.” Why? Can’t you put a condition in the callback function? Sep 4, 2020 at 8:45
  • Thanks for opening a new Q but I see you've made the filter names generic which means my answer doesn't make sense, it relied on the second filter being in the footer, which mean it run after the first filter, without this the solution doesn't work. You've instead asked for the generic arbitrary case in your question, for which again the answer is the same as your last question. You need to be specific about what you're asking. I'll edit the final_output hook back to wp_footer so it isn't confusing
    – Tom J Nowell
    Sep 4, 2020 at 9:27

1 Answer 1

0

Use both hooks, and call did_action to find out if the template hook fired or not.

https://developer.wordpress.org/reference/functions/did_action/

did_action will return the number of times a hook/action has fired. With this you can return early in the footer action

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.