WordPress hook directly after body tag

Viewed 69192

I'm having problems finding the right hook to use for my plugin. I'm trying to add a message to the top of each page by having my plugin add a function. What's the best hook to use? I want to insert content right after the <body> tag.


EDIT: I know it's three years later now, but here is a Trac ticket for anyone who is interested: http://core.trac.wordpress.org/ticket/12563


EDIT: July 31st, 2019

The linked Trac Ticket was closed as this feature was added in WordPress 5.2. You will find the Developer notes for this feature here (requires JavaScript enabled to display):

Miscellaneous Developer Updates in 5.2

I will not update the "correct answer" to one that mentions 5.2 for historical reasons, but rest assured that I'm aware and that the built-in hook is the correct one to use.

9 Answers

Changes, changes, changes. So it appears that since March 2019 (from WP 5.2) we have a little nicer way to do this.

There is a new function wp_body_open(). To support it, your theme has to call this function right after <body> opening tag:

<html>
  <head>

    ..
    ..

    <?php wp_head(); ?>

  </head>
  <body>

    <?php wp_body_open(); ?>

    ..
    ..

    <?php wp_footer(); ?>

  </body>
</html>

And then you can use it in the same way you use wp_head or wp_footer hooks to print anything just after <body>.

WordPress has now addressed this by adding the wp_body_open hook in version 5.2. You can now hook or inject into HTML body by doing:

<?php add_action('wp_body_open', function() { //some code to fire or inject HTML here }); ?>

Putting this in your functions.php file in your theme might be best for most basic users.

Related