wordpress 5.2 之后每一个主题应该使用的动作钩子 wp_body_open
这是一个简单的函数,类似于wp_head 和wp_footer 钩子,比如当WordPress开发人员想要插入谷歌分析脚本或任何其他脚本页面前端,可以通过wp_head或wp_footer注入代码:
<?php
function custom_code() {
return '<!-- some code -->';
}
add_action( 'wp_head', 'custom_code' );
?>
wp_head使用在<head>中,wp_footer使用在</body>前,wp 5.2前没有默认的钩子使用在<body>后以方便的添加代码,WordPress 5.2,新主题结构看起来应该像这样:
<?php // WordPress 5.2 Theme Structure ?>
<html>
<head>
..
..
<?php wp_head(); ?>
</head>
<body>
<?php wp_body_open(); ?>
..
..
<?php wp_footer(); ?>
</body>
</html>
Read more information in related WordPress Trac tickets: #42927, #12563 and #46679.
Updating Themes
If you are a theme developer you should add the newly introduces function to your theme.
Note that some themes have multiple <body> tags, depending on their structure. Those kind of themes should add the wp_body_open() next to the <body> tags.
5.2版本前兼容问题:
<?php
//To support the new function and action in WordPress versions prior to 5.2, you should register the new function by yourself in the theme’s functions.php file:
<?php
if ( ! function_exists( 'wp_body_open' ) ) {
/**
* Fire the wp_body_open action.
*
* Added for backwards compatibility to support WordPress versions prior to 5.2.0.
*/
function wp_body_open() {
/**
* Triggered after the opening <body> tag.
*/
do_action( 'wp_body_open' );
}
}
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
<?php
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' );
}
文章参考:https://generatewp.com/wordpress-5-2-action-that-every-theme-should-use/每每阅读英文文档的时候才觉得英文是多么重要。
理解阅读:
