WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to inject some elements directly after the <body> tag.

Is that possible using only WordPress hooks?

share|improve this question
Please, Nippysaurus, do it without hacking the heck of what not need to be hacked... @kaiser's the correct answer :) – brasofilo Nov 21 '12 at 3:45
I'll have to take your word on this ... I ended up going with a child template so didn't end up implementing any of these solutions :) Very new to WordPress development (this is my second site) so its interesting to see how to solve these sort of solutions. – Nippysaurus Nov 21 '12 at 4:45
up vote 5 down vote accepted

Just add a custom hook to your template:

<?php do_action( 'wpse73370_custom_hook' ); ?>
share|improve this answer

I could not find any working example online, but I got one solution and I hope it might help anyone.

 jQuery(document).ready( function($) {
  $('body').prepend('<h1>Hello world</h1>');


share|improve this answer
Just to let you know that, with that help I made this plugin woocomercescratchdiscount.themefantasy.com – Sabir Abdul Mar 10 '15 at 13:14

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.

share|improve this answer
And if the site visitor disabled javascript? – Ralf912 Nov 20 '12 at 23:38
This is the hackiest hack ever :p – Nippysaurus Nov 20 '12 at 23:53
@Nippysaurus Indeed (+1), but output buffering is nothing better. – kaiser Nov 21 '12 at 0:41
@kaiser You think of nested output buffering. This is sometimes a bit tricky. Using output buffering with a callback, is not so tricky because the callback will be called on every ob_* function call and before the ob_* function call. – Ralf912 Nov 21 '12 at 19:56

Yes, it's quite simple:

add_action( 'init', 'test_start_buffer', 0, 0 );

function test_start_buffer(){

    ob_start( 'test_get_buffer' );


function test_get_buffer( $buffer){

    return preg_replace( '#<body.+>#', '<body>', $buffer);


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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.