I’m currently writing a plugin in which users can select whether they want to insert a google analytics tag or a GTM tag (Google tag manager). I’ve already figured out how to insert the code after the tag.
At the moment the code gets inserted through a custom function in my theme’s function.php
and calling the function in the themes header.php
Header.php
<?php wp_after_body();?>
Functions.php
function wp_after_body() {
do_action('wp_after_body');
}
But I was wondering if there is a solution in which I can just use my plugin file to insert the code after the tag (So I don’t have to change the theme files everytime I use the plugin).
I’ve already tried this:
https://stackoverflow.com/a/27309880/7634982
Since you want your plugin to be theme independent you will have to rely on hooks that you may assume are there in any decently made theme. At the moment you can only rely on wp_head
and wp_footer
. A hook right after the <body>
tag is under discussion, but even if it would be declared standard today, there would still be thousands of existing themes not implementing it. So that’s no use for you.
The option you tried just buffers most of the page, letting you change the buffer’s content before it is printed. It should work, though it is far from elegant and could easily interfere with other plugins using some kind of buffering.
So, no, there is no direct WordPressy way to do this in a reliable way. What you could do in a plugin, however, is solve it with json. The idea is fairly simple, though it will require some work (and probably a learning curve).
Hooking into wp_head
add a jquery script file that adds a DOM-element right after the <body>
tag and use the rest api to call the function that you would normally generate the code that you want in that place.