wp_body_open()WP 5.2.0

Launches the hook wp_body_open. It should be used in the theme immediately after the opening tag <body>.

Since WP version 5.2, this function should be used in the theme (template) to allow developers to insert anything immediately after the <body> tag.

Theme developers should use the following functions in themes:

The structure of the HTML code will be as follows:

<html>
	<head>
		...

		<?php wp_head(); ?>
	</head>

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

		<?php wp_footer(); ?>
	</body>
</html>
Hooks from the function

Returns

null. Nothing (null).

Usage

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

	<?php wp_body_open(); ?>

	...

Examples

0

#1 Output the custom content after the body tag

It is required to display a message for unauthorized users with a call to log in.

Basic template structure, for example index.php

<html>

<head>
	... the contents of the head ...
</head>

<body>

	<?php wp_body_open(); ?>

	... the rest of the layout of the site ...

</body>

</html>

Solution

<?php

add_action( 'wp_body_open', 'display_message_for_unauthorized_users' );

function display_message_for_unauthorized_users() {

	if ( ! is_user_logged_in() ):
	?>

		<div class="message-for-unauthorized-users">
			<p>
				<a href="<?= wp_login_url() ?>">Authorize</a> to get more options!
			</p>
		</div>

	<?php
	endif;
}

The code is need to be inserted in functions.php file or in a plugin.

In place of this message can be anything TEXT, HTML, JS etc..

0

#2 Make sure my code is included

How can I use this to my advantage as a plugin developer? How to make sure my code is included if the WP version is 5.2+ but the theme is older and/or does not include wp_body_open?

Here is a working solution suggested by @danieliser on this ticket answer.

<?php 
add_action( 'wp_body_open', 'wpdocs_my_function' ); 
add_action( 'wp_footer', 'wpdocs_my_function' ); 

function wpdocs_my_function() { 

	if ( doing_action( 'wp_body_open' ) ) { 
		remove_action ( 'wp_footer', 'wpdocs_my_function' ); 
	}

	// do stuff.
}

This way if you want to include code from your plugin just after the body tag opened by a theme that is up to date with good practices, and if it’s not, your code gets included the old way with wp_footer.

Changelog

Since 5.2.0 Introduced.

wp_body_open() code WP 6.8.1

function wp_body_open() {
	/**
	 * Triggered after the opening body tag.
	 *
	 * @since 5.2.0
	 */
	do_action( 'wp_body_open' );
}