とりあえず作ったので共有
php
1<?php
2//ブロックを登録するときにfront-script、front-styleもparamに入れておく
3add_filter('init',function(){
4 wp_register_script('myblock-script','path/to/myblock/script.js');
5 wp_register_script('myblock-editor-script','path/to/myblock/editor-script.js');
6 wp_register_script('myblock-front-script','path/to/myblock/front-script.js');
7 wp_register_style('myblock-style','path/to/myblock/style.css');
8 wp_register_style('myblock-editor-style','path/to/myblock/editor-style.css');
9 wp_register_style('myblock-front-style','path/to/myblock/front-style.css');
10 register_block_type('my/block',[
11 'script'=>'myblock-script',
12 'editor-script'=>'myblock-editor-script',
13 'front-script'=>'myblock-front-script',
14 'style'=>'myblock-style',
15 'editor-style'=>'myblock-editor-style',
16 'front-style'=>'myblock-front-style',
17 ]);
18});
19//ブロックがレンダリングされる時にブロックタイプにfront-script、front-styleがあればenqueue
20add_filter('render_block_data',function($block,$source_block){
21 static $done=[];
22 if(in_array($block['blockName'],$done,true)){return $block;}
23 $block_type=WP_Block_Type_Registry::get_instance()->get_registered($block['blockName']);
24 if(!empty($block_type->front_style)){wp_enqueue_style($block_type->front_style);}
25 if(!empty($block_type->front_script)){wp_enqueue_script($block_type->front_script);}
26 $done[]=$block['blockName'];
27 return $block;
28},10,2);
29//管理画面ではfront-script、front-styleがあれば全てenqueue
30add_action('enqueue_block_editor_assets',function(){
31 $block_registry=WP_Block_Type_Registry::get_instance();
32 foreach($block_registry->get_all_registered() as $block_name=>$block_type){
33 if(!empty($block_type->front_style)){wp_enqueue_style($block_type->front_style);}
34 if(!empty($block_type->front_script)){wp_enqueue_script($block_type->front_script);}
35 }
36});
PHPのクラスは基本動的で好きにプロパティつけれるからできるけど
言語仕様としてこの辺きちんとされると動かなくなっちゃう
$block->attsの値によって実際使用しているコンポーネントの
jsとcssだけ読み込むとこまでやろうかどうか検討中