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
<body <?php body_class(); ?>>
<?php wp_body_open(); ?>
</body>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
add_action( 'wp_body_open', function() {
?>
<script>
// Your script code here
</script>
<?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
if ( ! function_exists( 'wp_body_open' ) ) {
function wp_body_open() {
do_action( 'wp_body_open' );
}
}
?>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.


