wp_body_open()WP 5.2.0

Fire the wp_body_open action.

See wp_body_open.

Hooks from the function

Return

null. Nothing (null).

Usage

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.4.3

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