WordPress hook directly after body tag

2020-02-09 00:19发布

I'm having problems finding the right hook to use for my plugin. I'm trying to add a message to the top of each page by having my plugin add a function. What's the best hook to use? I want to insert content right after the <body> tag.


EDIT: I know it's three years later now, but here is a Trac ticket for anyone who is interested: http://core.trac.wordpress.org/ticket/12563


EDIT: July 31st, 2019

The linked Trac Ticket was closed as this feature was added in WordPress 5.2. You will find the Developer notes for this feature here (requires JavaScript enabled to display):

Miscellaneous Developer Updates in 5.2

I will not update the "correct answer" to one that mentions 5.2 for historical reasons, but rest assured that I'm aware and that the built-in hook is the correct one to use.

标签: php wordpress
9条回答
萌系小妹纸
2楼-- · 2020-02-09 01:14

Alternatively, if you are creating the theme yourself and/or can modify it, you can create an action yourself using WordPress' do_action function. This is also how they create their other hooks. So basically in your theme, you would go where you want to, right after the <body> tag, and do something like:

do_action('after_body');

You can also pass arguments to the action callback, see the linked documentation for information.

Then afterwards, you would simply use the add_action function to hook onto it.

add_action('after_body', 'my_callback');

Hope that helps. Sorry if I misunderstood.

查看更多
趁早两清
3楼-- · 2020-02-09 01:14

Changes, changes, changes. So it appears that since March 2019 (from WP 5.2) we have a little nicer way to do this.

There is a new function wp_body_open(). To support it, your theme has to call this function right after <body> opening tag:

<html>
  <head>

    ..
    ..

    <?php wp_head(); ?>

  </head>
  <body>

    <?php wp_body_open(); ?>

    ..
    ..

    <?php wp_footer(); ?>

  </body>
</html>

And then you can use it in the same way you use wp_head or wp_footer hooks to print anything just after <body>.

查看更多
地球回转人心会变
4楼-- · 2020-02-09 01:14

A very, very, very dirty solution would be:

/* Insert tracking code or others directly after BODY opens */
add_filter('body_class', 'wps_add_tracking_body', PHP_INT_MAX); // make sure, that's the last filter in the queue
function wps_add_tracking_body($classes) {

  // close <body> tag, insert stuff, open some other tag with senseless variable      
  $classes[] = '"><script> /* do whatever */ </script><noscript></noscript novar="';

  return $classes;
}
查看更多
登录 后发表回答