Insert HTML just after tag

Twenty Twelve does not have any hooks that fire immediately after the opening <body> tag.

Therefore you in your child theme which extends the parent Twenty Twelve theme, copy the header.php across to your child theme directory.

Open the header.php file in your child theme and just after the opening body tag add an action hook which you can then hook onto via your functions.php file.

For example in your twenty-twelve-child/header.php file:

<body <?php body_class(); ?>>

<?php do_action('after_body_open_tag'); ?>

Then in your twenty-twelve-child/functions.php file:

function custom_content_after_body_open_tag() {

    ?>

    <div>My Custom Content</div>

    <?php

}

add_action('after_body_open_tag', 'custom_content_after_body_open_tag');

This will then render in your HTML as:

<body>
<div>My Custom Content</div>

Recommended reading:

https://developer.wordpress.org/reference/functions/do_action/

UPDATE: JULY, 2019

As commented by Junaid Bhura from WordPress 5.2 a new theme helper function wp_body_open has been introduced that is intended for use as per the likes of other helper functions wp_head and wp_footer.

For example:

<html>
  <head>

    <?php wp_head(); ?>
 
  </head>
  <body <?php body_class(); ?>>
 
    <?php wp_body_open(); ?>

     <!-- BODY CONTENT HERE -->
 
    <?php wp_footer(); ?>
 
  </body>
</html>

In your theme functions.php file (or suitably elsewhere)

function custom_content_after_body_open_tag() {

    ?>

    <div>My Custom Content</div>

    <?php

}

add_action('wp_body_open', 'custom_content_after_body_open_tag');

IMPORTANT

You should ensure that the hook exists within the theme that you are wanting to inject-into as this may not be widely adopted by the community, yet.

If NOT, you will still need to follow the principle of extending the theme with a child theme with the exception that YOU would use:

<?php wp_body_open(); ?>

…instead of OR in addition to:

<?php do_action('after_body_open_tag'); ?>

Recommended reading:

https://developer.wordpress.org/reference/functions/wp_body_open/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)