要有条件地注册脚本/样式,如果页面有某个块,您可以按照@将在来自similar question. 复制/粘贴,并对该问题进行一些修改:
add_action( \'enqueue_block_assets\', \'myplugin_enqueue_if_block_is_present\' ); // Can only be loaded in the footer
// add_action( \'wp_enqueue_scripts\', \'myplugin_enqueue_if_block_is_present\' ); // Can be loaded in the both in head and footer
function myplugin_enqueue_if_block_is_present(){
if ( has_block( \'my-plugin/my-block\' ) ) {
wp_enqueue_script(
\'myplugin_script\',
PATH_TO_ASSETS_FOLDER . \'frontend-script.js\',
array(),
\'1.0.0\',
true
);
}
}
如果需要从块中获取信息以便将某个样式或脚本排队,一种方法是将脚本/样式排队到块的渲染功能中。
Beware 尽管这样做有效,但我们将enqueue函数与render回调混合使用。另一个缺点是,当回调运行时,我们已经在帖子的内容中了。这意味着我们只能在页脚排队,而不能在头部排队。
add_action( \'init\', \'myplugin_register_block\' );
function myplugin_register_block() {
register_block_type(
\'my-plugin/my-block\',
array(
\'editor_script\' => PATH_TO_ASSETS_FOLDER . \'editor-script.js\',
\'render_callback\' => \'myplugin_render_callback\'
)
);
}
function myplugin_render_callback( $attributes, $content ) {
// Do not enqueue if we are in the editor.
// This will depend on your use case.
if ( is_admin() ) {
return $content;
}
wp_enqueue_style(
\'myplugin_style\',
PATH_TO_ASSETS_FOLDER . $attributes[\'some_attribute\'] . \'-style.css\',
array(),
\'1.0.0\'
);
return $content;
}