wp_body_open()

Fires the wp_body_open action.

Description

See ‘wp_body_open’.

Source

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

Hooks

do_action( ‘wp_body_open’ )

Triggered after the opening body tag.

Changelog

VersionDescription
5.2.0Introduced.

User Contributed Notes

  1. Skip to note 6 content

    WordPress theme developers should use `wp_head()`, `wp_body_open()` and `wp_footer()` functions in their themes (read this for more information).

    The new WordPress theme structure:

    <html>
      <head>
    
        ..
        ..
    
        <?php wp_head(); ?>
    
      </head>
      <body>
    
        <?php wp_body_open(); ?>
    
        ..
        ..
    
        <?php wp_footer(); ?>
    
      </body>
    </html>
  2. Skip to note 8 content

    I Think This is the best way for add wp_body_open(); function for backwards compatibility

    Step 1 : Checked if function is exits, if not exits then make a function called wp_body_open();

    Example:

    if ( ! function_exists( 'wp_body_open' ) ) {
        function wp_body_open() {
            do_action( 'wp_body_open' );
        }
    }

    Then put the function after the body tag.

    Example:

    <html>
      <head>
     
        ..
        ..
     
        <?php wp_head(); ?>
     
      </head>
      <body>
     
        <?php wp_body_open(); ?>
     
        ..
        ..
     
        <?php wp_footer(); ?>
     
      </body>
    </html>
  3. Skip to note 9 content

    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.

  4. Skip to note 10 content

    Custom Theme Hooks

    Many themes use their own custom actions at the beginning of body tag. They should consider migrating to the core wp_body_open action.

    For backwards compatibility, when injecting custom code, theme developers can use conditional logic to hook to the right action

    function custom_code() {
        return '<!-- some code -->';
    }
    
    if ( did_action( 'wp_body_open' ) ) {
        add_action( 'wp_body_open', 'custom_code' );
    } else {
        add_action( 'custom_theme_hook', 'custom_code' );
    }

You must log in before being able to contribute a note or feedback.