How to Add Code After the Body Tag in WordPress

On the website, we usually need to insert code after the body tag. Normally, this is an unseen JavaScript code within a script tag. External services like Google Analytics, Google Tag Manager, Google Adsense, Facebook, etc. give you a script that needs to be added before the closing of the head tag and after immediately opening of the body element.

WordPress provides wp_head() function which is used to inject code before closing the head tag. Another function provided by WordPress is wp_footer() which is used to add code before the closing of the body element(not after the body open). So far, WordPress developers use wp_footer() to inject code in body tag or add code statically after the opening of the body element. But, both these options are not recommended.

Adding code statically makes sense as per recommendations from external services. But this technique would then stop us from updating a theme.

Fortunately, WordPress 5.2 introduces a new function called wp_body_open(). This function triggers wp_body_open action and useful to place code after the opening of the body element. That being said, let’s see how to inject code immediately after opening a body tag in WordPress.

Add Code After the Body Tag in WordPress

If you are using the latest version of WordPress then you should add the wp_body_open() method next to your body tag as shown below.

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

After this, you can use the action wp_body_open to add your code in the place of wp_body_open(). In other words, you can inject your code immediately after opening the body tag. You can use this action as follows:

add_action('wp_body_open', 'add_code_on_body_open');
function add_code_on_body_open() {
    echo '<script>Your code here</script>';

That’s it! It is that simple. This code works well with the WordPress version >= 5.2. If you are using an older version of WordPress then you can define the wp_body_open method as follows.

if ( ! function_exists( 'wp_body_open' ) ) {
    function wp_body_open() {
        do_action( 'wp_body_open' );

Now, add the method wp_body_open() after the body element and use the action same as shown above.

This is a clean and efficient way to inject your code after the opening of the body tag. I encourage WordPress developers to use this technique on their websites. Read more about this update on the documentation.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *