WP Body Open Hook

WP Body Open Hook
WP Body Open Hook

Learn how the wp_body_open() function simplifies adding content to the WordPress body tag without editing theme files. Introduced in WordPress 5.2, it enhances flexibility, keeps your code clean, and ensures update-safe customizations.

Function Name: wp_body_open()
Supported Version: WordPress 5.2+

If you’ve ever needed to drop a script or tracking pixel right after the opening <body> tag, you used to have one ugly option: edit the theme’s header.php and watch your change vanish on the next update. WordPress 5.2 fixed that in 2019 with wp_body_open() and its matching wp_body_open action hook, a clean, update-safe spot for a plugin or your own code to add content right after <body> without touching the theme.

How to add it

The function lives in the theme, right after the opening <body> tag:

PHP
<?php
&lt;body &lt;?php body_class(); ?&gt;&gt;
    &lt;?php wp_body_open(); ?&gt;
&lt;/body&gt;

That’s the theme author’s job, not yours. wp_body_open() prints nothing on its own; it just fires the wp_body_open action so anyone can hook in.

Hook in your own code

Want to inject a script without editing theme files? Hook the action:

PHP
<?php
add_action( 'wp_body_open', function() {
    ?&gt;
    &lt;script&gt;
        // Your script code here
    &lt;/script&gt;
    &lt;?php
});

It’s update-safe, and it works from a plugin or a child theme’s functions.php.

What belongs here

Keep it to non-visible things: analytics, tracking pixels, meta tags. Printing visible text or images this early can fight your layout, so don’t.

Older WordPress versions

If your code has to run on pre-5.2 sites, define the function only when it’s missing:

PHP
<?php
&lt;?php
if ( ! function_exists( 'wp_body_open' ) ) {
    function wp_body_open() {
        do_action( 'wp_body_open' );
    }
}
?&gt;

One honest caveat: the hook only fires if the active theme actually calls wp_body_open(). Plenty of older or custom themes never added it, so if your snippet does nothing, check the theme’s header first.

Next: WordPress Hooks Insert Code After Body

Leave a Comment

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


Scroll to Top