How to Add a Script or Content After the Opening Body Tag in WordPress

Add a script after the opening body tag to enable Google Analytics or Google Tag Manager even when JavaScript is not enabled.

interwebing02 How-To

Step 1: Add an action hook after the opening body tag

In most WordPress themes the opening body tag is inserted in one template file, typically a header or masthead file such as header.php or masthead.php. In this file you should see a line that looks like this:

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

Just after that line is where you want to insert your action hook. After adding the action hook it should look like this:

<body <?php body_class(); ?>>
    <?php do_action('insert_after_open_body'); ?>

With that you have added an action hook called ‘insert_after_open_body’, however you can name it anything you like, just be sure you are using that same name when adding the action in later.

Step 2: Call your action from another file

Typically you would call an action from another file such as functions.php. Using your new action is very simple. Here is an example:

<?php
add_action( 'insert_after_open_body', 'my_content_for_after_open_body' );
function my_content_for_after_open_body() { ?>
    <script>Awesome Script Content</script>
<?php
}

Above you are calling your custom action we defined in step 1 and using it to run another function we have defined in step 2. The first line with the ‘add_action’ function is telling WordPress to call the ‘my_content_for_after_open_body’ function when it gets to the ‘do_action’ function with the same name we defined in step 1. Within the ‘my_content_for_after_open_body’ function we can add just about anything. We can have complex PHP or JavaScript in there, or just some simple HTML. By using an action we are able to tell WordPress exactly where and when we want to run it.