嗯,如果我没有记错的话,只有在使用块时,才应该加载在php register\\u block\\u类型调用中注册的样式和脚本。
如果仅当存在类型为“my awesome/block type”的块时,才想加载要排队的其他脚本或样式,可以在wp\\U enqueue\\U脚本函数中使用has\\U block函数,如下所示:
add_action(\'wp_enqueue_scripts\',\'enqueue_if_block_is_present\');
function enqueue_if_block_is_present(){
if(is_singular()){
//We only want the script if it\'s a singular page
$id = get_the_ID();
if(has_block(\'my-awesome/block-type\',$id)){
wp_enqueue_script(\'my-awesome-script\',$path_of_script,$needed_scripts,$version_of_script,$load_in_footer);
}
}
}
如果还希望在多个视图(如类别存档或博客页面)上加载脚本,可以挂接到\\u内容过滤器并将脚本排队:
add_filter(\'the_content\',\'enqueue_my_awesome_script_if_there_is_block\');
function enqueue_my_awesome_script_if_there_is_block($content = ""){
if(has_block(\'my-awesome/block-type\')){
wp_enqueue_script(\'my-awesome-script\',$path_of_script,$needed_scripts,$version_of_script,true);
//Be aware that for this to work, the load_in_footer MUST be set to true, as
//the scripts for the header are already echoed out at this point
}
return $content;
}
快乐的编码!