I am afraid this is not possible at the moment. This is completely on the Theme territory, and you would always depend on the Theme code.
BUT!! There is a simple hack you can use, for a not complicated code insertion. I say it is a hack, and you will see why.
The only thing you can count on that will exist in 99.99% of the Themes is <body <?php body_class(); ?>>
. So we can use a filter hook to add another 'class' to the body tag, except... it won't be a class. Look at this code:
add_filter( 'body_class', function ( $classes ) {
return array_merge(
$classes,
array( '">
<iframe src="//www.googletagmanager.com/ns.html?id=XXX-XXXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe>
<input type="hidden' // Important to handle the closing of the body element
)
);
} );
What have we done here? We have first added ">
to close the body
element. Then you can insert whatever HTML you want. The last part is also mandatory, to handle the actual closing of the body
element, we need to create something that won't break our template, so a hidden input field should work well. We add <input type="hidden
, but without closing with ">
because the body_class()
function will do it for us.
Note that there is a possibility this would collide with some other filters on body_class
, depending on the priority. To handle this, you could wrap this into another action hook that will fire after the theme is loaded, for instance get_header
. In that case, the full code would be:
add_action( 'get_header', function() {
add_filter( 'body_class', function ( $classes ) {
return array_merge(
$classes,
array( '">
<iframe src="//www.googletagmanager.com/ns.html?id=XXX-XXXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe>
<input type="hidden' // Important to handle the closing of the body element
) );
} );
});
Even though this possibly does what you want, I can't really recommend this.