wp_body_open – WordPress action that every theme should use (5.2+)

One of the major problems faced by developers before the release of WordPress 5.2 was the inability to inject scripts or styles at the beginning of the <body> tag. This was a major drawback in WordPress core as marketers need to register tracking codes at the beginning of the body tag before any content is displayed.

WordPress 5.2 added a new function, wp_body_open() and thereby introducing the wp_body_open hook. It may seem to be a minor function but it has a huge impact on theme and plugin developers that inject code to WordPress themes. Sadly some developers are not yet familiar with the wp_body_open function and the hook, as this is relatively new compared to the similar set of functions wp_head and wp_footer.

The wp_body_open function

The wp_head function triggers the wp_head action and wp_footer triggers the wp_footer action. Similarly, wp_body_open function triggers an action: wp_body_open.  All the default themes use them in their header.php file. The main use case of this action is to add script tags after the opening body tag. You can use the same for adding other unseen elements after the body tag. Adding HTML content (visible) is not recommended, as this may break the site layout. 

For example, you can use this action hook to add the Google Tag Manager code.

After using this hook you can see a similar output in your browser with Twenty Twenty theme.

If you are a theme developer, make sure to add wp_body_open in your theme just like wp_head and wp_footer. You can add wp_body_open function after the body tag in your theme like below:

Backwards Compatibility

Please note that if you want your theme to be backward compatible (below WordPress 5.2), please make sure to add a Shim in your theme’s functions.php file. If you don’t make it backward compatible, then calling wp_body_open function may result in a fatal PHP error. An example Shim is given below:

So finally we have an in-built system to output code after <body>. WordPress developers who previously had to resort to clumsy workarounds can now breathe a sigh of relief!

The WP Week Newsletter

A weekly newsletter covering updates from the WordPress ecosystem that are relevant and helpful for WordPress agencies, developers, and enthusiasts

Leave your comment

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