I would like to inject some elements directly after the <body>
tag.
Is that possible using only WordPress hooks?
I would like to inject some elements directly after the <body>
tag.
Is that possible using only WordPress hooks?
You must be logged in to post a comment.
Just add a custom hook to your template:
WordPress 5.2.0 introduced the
wp_body_open
hook (detailed in the WordPress codex)After reading this answer I’ve made this.
The first two filters “shutdown” and “final_output” are the core functions. Could be part of a plugin. After they are created you can use the new after_body filter to add what you want to the after body.
In This case i added a simple div, so it ended up like this:
And what is also interesting is with this regex you don’t need to worry about damaging what is inside the body. A class for instance or any other thing
I could not find any working example online, but I got one solution and I hope it might help anyone.
https://wordpress.org/support/topic/add_action-right-after-ltbodygt-tag
If you are using Genesis by StudioPress, there is a hook you can use like the one I use for facebook plugins:
That seems to work for me. It is essentially the exact same thing as adding your own hook, like the #1 answer (which I agree is the best).
However…. if you are like me, and slap together sites using whatever template the client picked out, I don’t like to add my own hooks like that. I keep all my stuff in a separate directory and link it to the functions.php. So, I would use the jquery solution to just add it to the dom after the load.
However, I tested Ralf912’s output buffer idea. That’s very cool. I’d say, if you need to make sure your code is executed correctly and on the same page and it’s 100% has to be there, and you don’t want to mess with the template, that’s a good idea.
You can create a plugin that is based on JavaScript and uses
prependTo
in order to place a tag right after the starting body tag. Check this out for a reference.Yes, it’s quite simple:
The first function will register a callback for the output buffering. The second function is the callback and will modify and return the HTML. Please read the PHP manual output bufferuing for more informations.