wp_enqueue_block_support_styles()
云策文档标注
概述
wp_enqueue_block_support_styles() 函数用于根据活动主题类型,将内联样式挂载到适当位置。它通过判断是否为块主题,动态选择 wp_head 或 wp_footer 钩子来输出 CSS 样式。
关键要点
- 函数根据 wp_is_block_theme() 判断主题类型:块主题样式挂载到 wp_head,经典主题样式挂载到 wp_footer。
- 接受两个参数:$style(必需,CSS 样式字符串)和 $priority(可选,优先级,默认 10)。
- 从 WordPress 6.1.0 版本开始添加了 $priority 参数,允许自定义样式加载优先级。
代码示例
function wp_enqueue_block_support_styles( $style, $priority = 10 ) {
$action_hook_name = 'wp_footer';
if ( wp_is_block_theme() ) {
$action_hook_name = 'wp_head';
}
add_action(
$action_hook_name,
static function () use ( $style ) {
echo "<style>" . $style . "</style>n";
},
$priority
);
}注意事项
- 对于块主题,样式在头部加载;对于经典主题,样式在正文加载,因为 wp_head 动作发生在 render_block 之前。
- 此函数自 WordPress 5.9.1 版本引入,6.1.0 版本增加了 $priority 参数。
原文内容
Hooks inline styles in the proper place, depending on the active theme.
Parameters
$stylestringrequired-
String containing the CSS styles to be added.
$priorityintoptional-
To set the priority for the add_action.
Default:
10
Source
function wp_enqueue_block_support_styles( $style, $priority = 10 ) {
$action_hook_name = 'wp_footer';
if ( wp_is_block_theme() ) {
$action_hook_name = 'wp_head';
}
add_action(
$action_hook_name,
static function () use ( $style ) {
echo "<style>$style</style>n";
},
$priority
);
}