How to add code after body tag in WordPress

To add code after the body tag in WordPress, you can use the wp_body_open() function. This function was introduced in WordPress 5.2 and is specifically designed to add content after the opening <body> tag.

Here’s an example of how to use the wp_body_open() function to add code after the body tag in WordPress:

  1. Open your theme’s functions.php file.
  2. Add the following code to the file:

function my_custom_code() {
echo '<!-- Your code here -->';
add_action( 'wp_body_open', 'my_custom_code' );

  1. Replace the <!-- Your code here --> comment with your own HTML, CSS, or JavaScript code.
  2. Save the functions.php file.

This code creates a new function called my_custom_code() that echoes your custom code. The add_action() function is used to add the my_custom_code() function to the wp_body_open hook, which ensures that your code is output after the opening <body> tag.

Note that it’s important to use the wp_body_open() function instead of the wp_head() function or any other hook. Using the wp_body_open() function ensures that your code is placed in the correct location within the HTML structure of the page.

Hope you enjoyed this tutorial and happy coding!

Leave a Comment

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