mirrored from git://develop.git.wordpress.org/
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
blocks.php
2192 lines (1977 loc) · 76.3 KB
/
blocks.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Functions related to registering and parsing blocks.
*
* @package WordPress
* @subpackage Blocks
* @since 5.0.0
*/
/**
* Removes the block asset's path prefix if provided.
*
* @since 5.5.0
*
* @param string $asset_handle_or_path Asset handle or prefixed path.
* @return string Path without the prefix or the original value.
*/
function remove_block_asset_path_prefix( $asset_handle_or_path ) {
$path_prefix = 'file:';
if ( ! str_starts_with( $asset_handle_or_path, $path_prefix ) ) {
return $asset_handle_or_path;
}
$path = substr(
$asset_handle_or_path,
strlen( $path_prefix )
);
if ( str_starts_with( $path, './' ) ) {
$path = substr( $path, 2 );
}
return $path;
}
/**
* Generates the name for an asset based on the name of the block
* and the field name provided.
*
* @since 5.5.0
* @since 6.1.0 Added `$index` parameter.
* @since 6.5.0 Added support for `viewScriptModule` field.
*
* @param string $block_name Name of the block.
* @param string $field_name Name of the metadata field.
* @param int $index Optional. Index of the asset when multiple items passed.
* Default 0.
* @return string Generated asset name for the block's field.
*/
function generate_block_asset_handle( $block_name, $field_name, $index = 0 ) {
if ( str_starts_with( $block_name, 'core/' ) ) {
$asset_handle = str_replace( 'core/', 'wp-block-', $block_name );
if ( str_starts_with( $field_name, 'editor' ) ) {
$asset_handle .= '-editor';
}
if ( str_starts_with( $field_name, 'view' ) ) {
$asset_handle .= '-view';
}
if ( str_ends_with( strtolower( $field_name ), 'scriptmodule' ) ) {
$asset_handle .= '-script-module';
}
if ( $index > 0 ) {
$asset_handle .= '-' . ( $index + 1 );
}
return $asset_handle;
}
$field_mappings = array(
'editorScript' => 'editor-script',
'editorStyle' => 'editor-style',
'script' => 'script',
'style' => 'style',
'viewScript' => 'view-script',
'viewScriptModule' => 'view-script-module',
'viewStyle' => 'view-style',
);
$asset_handle = str_replace( '/', '-', $block_name ) .
'-' . $field_mappings[ $field_name ];
if ( $index > 0 ) {
$asset_handle .= '-' . ( $index + 1 );
}
return $asset_handle;
}
/**
* Gets the URL to a block asset.
*
* @since 6.4.0
*
* @param string $path A normalized path to a block asset.
* @return string|false The URL to the block asset or false on failure.
*/
function get_block_asset_url( $path ) {
if ( empty( $path ) ) {
return false;
}
// Path needs to be normalized to work in Windows env.
static $wpinc_path_norm = '';
if ( ! $wpinc_path_norm ) {
$wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
}
if ( str_starts_with( $path, $wpinc_path_norm ) ) {
return includes_url( str_replace( $wpinc_path_norm, '', $path ) );
}
static $template_paths_norm = array();
$template = get_template();
if ( ! isset( $template_paths_norm[ $template ] ) ) {
$template_paths_norm[ $template ] = wp_normalize_path( get_template_directory() );
}
if ( str_starts_with( $path, trailingslashit( $template_paths_norm[ $template ] ) ) ) {
return get_theme_file_uri( str_replace( $template_paths_norm[ $template ], '', $path ) );
}
if ( is_child_theme() ) {
$stylesheet = get_stylesheet();
if ( ! isset( $template_paths_norm[ $stylesheet ] ) ) {
$template_paths_norm[ $stylesheet ] = wp_normalize_path( get_stylesheet_directory() );
}
if ( str_starts_with( $path, trailingslashit( $template_paths_norm[ $stylesheet ] ) ) ) {
return get_theme_file_uri( str_replace( $template_paths_norm[ $stylesheet ], '', $path ) );
}
}
return plugins_url( basename( $path ), $path );
}
/**
* Finds a script module ID for the selected block metadata field. It detects
* when a path to file was provided and optionally finds a corresponding asset
* file with details necessary to register the script module under with an
* automatically generated module ID. It returns unprocessed script module
* ID otherwise.
*
* @since 6.5.0
*
* @param array $metadata Block metadata.
* @param string $field_name Field name to pick from metadata.
* @param int $index Optional. Index of the script module ID to register when multiple
* items passed. Default 0.
* @return string|false Script module ID or false on failure.
*/
function register_block_script_module_id( $metadata, $field_name, $index = 0 ) {
if ( empty( $metadata[ $field_name ] ) ) {
return false;
}
$module_id = $metadata[ $field_name ];
if ( is_array( $module_id ) ) {
if ( empty( $module_id[ $index ] ) ) {
return false;
}
$module_id = $module_id[ $index ];
}
$module_path = remove_block_asset_path_prefix( $module_id );
if ( $module_id === $module_path ) {
return $module_id;
}
$path = dirname( $metadata['file'] );
$module_asset_raw_path = $path . '/' . substr_replace( $module_path, '.asset.php', - strlen( '.js' ) );
$module_id = generate_block_asset_handle( $metadata['name'], $field_name, $index );
$module_asset_path = wp_normalize_path(
realpath( $module_asset_raw_path )
);
$module_path_norm = wp_normalize_path( realpath( $path . '/' . $module_path ) );
$module_uri = get_block_asset_url( $module_path_norm );
$module_asset = ! empty( $module_asset_path ) ? require $module_asset_path : array();
$module_dependencies = isset( $module_asset['dependencies'] ) ? $module_asset['dependencies'] : array();
wp_register_script_module(
$module_id,
$module_uri,
$module_dependencies,
isset( $module_asset['version'] ) ? $module_asset['version'] : false
);
return $module_id;
}
/**
* Finds a script handle for the selected block metadata field. It detects
* when a path to file was provided and optionally finds a corresponding asset
* file with details necessary to register the script under automatically
* generated handle name. It returns unprocessed script handle otherwise.
*
* @since 5.5.0
* @since 6.1.0 Added `$index` parameter.
* @since 6.5.0 The asset file is optional.
*
* @param array $metadata Block metadata.
* @param string $field_name Field name to pick from metadata.
* @param int $index Optional. Index of the script to register when multiple items passed.
* Default 0.
* @return string|false Script handle provided directly or created through
* script's registration, or false on failure.
*/
function register_block_script_handle( $metadata, $field_name, $index = 0 ) {
if ( empty( $metadata[ $field_name ] ) ) {
return false;
}
$script_handle = $metadata[ $field_name ];
if ( is_array( $script_handle ) ) {
if ( empty( $script_handle[ $index ] ) ) {
return false;
}
$script_handle = $script_handle[ $index ];
}
$script_path = remove_block_asset_path_prefix( $script_handle );
if ( $script_handle === $script_path ) {
return $script_handle;
}
$path = dirname( $metadata['file'] );
$script_asset_raw_path = $path . '/' . substr_replace( $script_path, '.asset.php', - strlen( '.js' ) );
$script_handle = generate_block_asset_handle( $metadata['name'], $field_name, $index );
$script_asset_path = wp_normalize_path(
realpath( $script_asset_raw_path )
);
$script_path_norm = wp_normalize_path( realpath( $path . '/' . $script_path ) );
$script_uri = get_block_asset_url( $script_path_norm );
$script_args = array();
if ( 'viewScript' === $field_name && $script_uri ) {
$script_args['strategy'] = 'defer';
}
// Asset file for blocks is optional. See https://core.trac.wordpress.org/ticket/60460.
$script_asset = ! empty( $script_asset_path ) ? require $script_asset_path : array();
$script_dependencies = isset( $script_asset['dependencies'] ) ? $script_asset['dependencies'] : array();
$result = wp_register_script(
$script_handle,
$script_uri,
$script_dependencies,
isset( $script_asset['version'] ) ? $script_asset['version'] : false,
$script_args
);
if ( ! $result ) {
return false;
}
if ( ! empty( $metadata['textdomain'] ) && in_array( 'wp-i18n', $script_dependencies, true ) ) {
wp_set_script_translations( $script_handle, $metadata['textdomain'] );
}
return $script_handle;
}
/**
* Finds a style handle for the block metadata field. It detects when a path
* to file was provided and registers the style under automatically
* generated handle name. It returns unprocessed style handle otherwise.
*
* @since 5.5.0
* @since 6.1.0 Added `$index` parameter.
*
* @param array $metadata Block metadata.
* @param string $field_name Field name to pick from metadata.
* @param int $index Optional. Index of the style to register when multiple items passed.
* Default 0.
* @return string|false Style handle provided directly or created through
* style's registration, or false on failure.
*/
function register_block_style_handle( $metadata, $field_name, $index = 0 ) {
if ( empty( $metadata[ $field_name ] ) ) {
return false;
}
$style_handle = $metadata[ $field_name ];
if ( is_array( $style_handle ) ) {
if ( empty( $style_handle[ $index ] ) ) {
return false;
}
$style_handle = $style_handle[ $index ];
}
$style_handle_name = generate_block_asset_handle( $metadata['name'], $field_name, $index );
// If the style handle is already registered, skip re-registering.
if ( wp_style_is( $style_handle_name, 'registered' ) ) {
return $style_handle_name;
}
static $wpinc_path_norm = '';
if ( ! $wpinc_path_norm ) {
$wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) );
}
$is_core_block = isset( $metadata['file'] ) && str_starts_with( $metadata['file'], $wpinc_path_norm );
// Skip registering individual styles for each core block when a bundled version provided.
if ( $is_core_block && ! wp_should_load_separate_core_block_assets() ) {
return false;
}
$style_path = remove_block_asset_path_prefix( $style_handle );
$is_style_handle = $style_handle === $style_path;
// Allow only passing style handles for core blocks.
if ( $is_core_block && ! $is_style_handle ) {
return false;
}
// Return the style handle unless it's the first item for every core block that requires special treatment.
if ( $is_style_handle && ! ( $is_core_block && 0 === $index ) ) {
return $style_handle;
}
// Check whether styles should have a ".min" suffix or not.
$suffix = SCRIPT_DEBUG ? '' : '.min';
if ( $is_core_block ) {
$style_path = ( 'editorStyle' === $field_name ) ? "editor{$suffix}.css" : "style{$suffix}.css";
}
$style_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $style_path ) );
$style_uri = get_block_asset_url( $style_path_norm );
$version = ! $is_core_block && isset( $metadata['version'] ) ? $metadata['version'] : false;
$result = wp_register_style(
$style_handle_name,
$style_uri,
array(),
$version
);
if ( ! $result ) {
return false;
}
if ( $style_uri ) {
wp_style_add_data( $style_handle_name, 'path', $style_path_norm );
if ( $is_core_block ) {
$rtl_file = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $style_path_norm );
} else {
$rtl_file = str_replace( '.css', '-rtl.css', $style_path_norm );
}
if ( is_rtl() && file_exists( $rtl_file ) ) {
wp_style_add_data( $style_handle_name, 'rtl', 'replace' );
wp_style_add_data( $style_handle_name, 'suffix', $suffix );
wp_style_add_data( $style_handle_name, 'path', $rtl_file );
}
}
return $style_handle_name;
}
/**
* Gets i18n schema for block's metadata read from `block.json` file.
*
* @since 5.9.0
*
* @return object The schema for block's metadata.
*/
function get_block_metadata_i18n_schema() {
static $i18n_block_schema;
if ( ! isset( $i18n_block_schema ) ) {
$i18n_block_schema = wp_json_file_decode( __DIR__ . '/block-i18n.json' );
}
return $i18n_block_schema;
}
/**
* Registers a block type from the metadata stored in the `block.json` file.
*
* @since 5.5.0
* @since 5.7.0 Added support for `textdomain` field and i18n handling for all translatable fields.
* @since 5.9.0 Added support for `variations` and `viewScript` fields.
* @since 6.1.0 Added support for `render` field.
* @since 6.3.0 Added `selectors` field.
* @since 6.4.0 Added support for `blockHooks` field.
* @since 6.5.0 Added support for `allowedBlocks`, `viewScriptModule`, and `viewStyle` fields.
*
* @param string $file_or_folder Path to the JSON file with metadata definition for
* the block or path to the folder where the `block.json` file is located.
* If providing the path to a JSON file, the filename must end with `block.json`.
* @param array $args Optional. Array of block type arguments. Accepts any public property
* of `WP_Block_Type`. See WP_Block_Type::__construct() for information
* on accepted arguments. Default empty array.
* @return WP_Block_Type|false The registered block type on success, or false on failure.
*/
function register_block_type_from_metadata( $file_or_folder, $args = array() ) {
/*
* Get an array of metadata from a PHP file.
* This improves performance for core blocks as it's only necessary to read a single PHP file
* instead of reading a JSON file per-block, and then decoding from JSON to PHP.
* Using a static variable ensures that the metadata is only read once per request.
*/
static $core_blocks_meta;
if ( ! $core_blocks_meta ) {
$core_blocks_meta = require ABSPATH . WPINC . '/blocks/blocks-json.php';
}
$metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ?
trailingslashit( $file_or_folder ) . 'block.json' :
$file_or_folder;
$is_core_block = str_starts_with( $file_or_folder, ABSPATH . WPINC );
// If the block is not a core block, the metadata file must exist.
$metadata_file_exists = $is_core_block || file_exists( $metadata_file );
if ( ! $metadata_file_exists && empty( $args['name'] ) ) {
return false;
}
// Try to get metadata from the static cache for core blocks.
$metadata = array();
if ( $is_core_block ) {
$core_block_name = str_replace( ABSPATH . WPINC . '/blocks/', '', $file_or_folder );
if ( ! empty( $core_blocks_meta[ $core_block_name ] ) ) {
$metadata = $core_blocks_meta[ $core_block_name ];
}
}
// If metadata is not found in the static cache, read it from the file.
if ( $metadata_file_exists && empty( $metadata ) ) {
$metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) );
}
if ( ! is_array( $metadata ) || ( empty( $metadata['name'] ) && empty( $args['name'] ) ) ) {
return false;
}
$metadata['file'] = $metadata_file_exists ? wp_normalize_path( realpath( $metadata_file ) ) : null;
/**
* Filters the metadata provided for registering a block type.
*
* @since 5.7.0
*
* @param array $metadata Metadata for registering a block type.
*/
$metadata = apply_filters( 'block_type_metadata', $metadata );
// Add `style` and `editor_style` for core blocks if missing.
if ( ! empty( $metadata['name'] ) && str_starts_with( $metadata['name'], 'core/' ) ) {
$block_name = str_replace( 'core/', '', $metadata['name'] );
if ( ! isset( $metadata['style'] ) ) {
$metadata['style'] = "wp-block-$block_name";
}
if ( current_theme_supports( 'wp-block-styles' ) && wp_should_load_separate_core_block_assets() ) {
$metadata['style'] = (array) $metadata['style'];
$metadata['style'][] = "wp-block-{$block_name}-theme";
}
if ( ! isset( $metadata['editorStyle'] ) ) {
$metadata['editorStyle'] = "wp-block-{$block_name}-editor";
}
}
$settings = array();
$property_mappings = array(
'apiVersion' => 'api_version',
'name' => 'name',
'title' => 'title',
'category' => 'category',
'parent' => 'parent',
'ancestor' => 'ancestor',
'icon' => 'icon',
'description' => 'description',
'keywords' => 'keywords',
'attributes' => 'attributes',
'providesContext' => 'provides_context',
'usesContext' => 'uses_context',
'selectors' => 'selectors',
'supports' => 'supports',
'styles' => 'styles',
'variations' => 'variations',
'example' => 'example',
'allowedBlocks' => 'allowed_blocks',
);
$textdomain = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null;
$i18n_schema = get_block_metadata_i18n_schema();
foreach ( $property_mappings as $key => $mapped_key ) {
if ( isset( $metadata[ $key ] ) ) {
$settings[ $mapped_key ] = $metadata[ $key ];
if ( $metadata_file_exists && $textdomain && isset( $i18n_schema->$key ) ) {
$settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain );
}
}
}
if ( ! empty( $metadata['render'] ) ) {
$template_path = wp_normalize_path(
realpath(
dirname( $metadata['file'] ) . '/' .
remove_block_asset_path_prefix( $metadata['render'] )
)
);
if ( $template_path ) {
/**
* Renders the block on the server.
*
* @since 6.1.0
*
* @param array $attributes Block attributes.
* @param string $content Block default content.
* @param WP_Block $block Block instance.
*
* @return string Returns the block content.
*/
$settings['render_callback'] = static function ( $attributes, $content, $block ) use ( $template_path ) {
ob_start();
require $template_path;
return ob_get_clean();
};
}
}
$settings = array_merge( $settings, $args );
$script_fields = array(
'editorScript' => 'editor_script_handles',
'script' => 'script_handles',
'viewScript' => 'view_script_handles',
);
foreach ( $script_fields as $metadata_field_name => $settings_field_name ) {
if ( ! empty( $settings[ $metadata_field_name ] ) ) {
$metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
}
if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
$scripts = $metadata[ $metadata_field_name ];
$processed_scripts = array();
if ( is_array( $scripts ) ) {
for ( $index = 0; $index < count( $scripts ); $index++ ) {
$result = register_block_script_handle(
$metadata,
$metadata_field_name,
$index
);
if ( $result ) {
$processed_scripts[] = $result;
}
}
} else {
$result = register_block_script_handle(
$metadata,
$metadata_field_name
);
if ( $result ) {
$processed_scripts[] = $result;
}
}
$settings[ $settings_field_name ] = $processed_scripts;
}
}
$module_fields = array(
'viewScriptModule' => 'view_script_module_ids',
);
foreach ( $module_fields as $metadata_field_name => $settings_field_name ) {
if ( ! empty( $settings[ $metadata_field_name ] ) ) {
$metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
}
if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
$modules = $metadata[ $metadata_field_name ];
$processed_modules = array();
if ( is_array( $modules ) ) {
for ( $index = 0; $index < count( $modules ); $index++ ) {
$result = register_block_script_module_id(
$metadata,
$metadata_field_name,
$index
);
if ( $result ) {
$processed_modules[] = $result;
}
}
} else {
$result = register_block_script_module_id(
$metadata,
$metadata_field_name
);
if ( $result ) {
$processed_modules[] = $result;
}
}
$settings[ $settings_field_name ] = $processed_modules;
}
}
$style_fields = array(
'editorStyle' => 'editor_style_handles',
'style' => 'style_handles',
'viewStyle' => 'view_style_handles',
);
foreach ( $style_fields as $metadata_field_name => $settings_field_name ) {
if ( ! empty( $settings[ $metadata_field_name ] ) ) {
$metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ];
}
if ( ! empty( $metadata[ $metadata_field_name ] ) ) {
$styles = $metadata[ $metadata_field_name ];
$processed_styles = array();
if ( is_array( $styles ) ) {
for ( $index = 0; $index < count( $styles ); $index++ ) {
$result = register_block_style_handle(
$metadata,
$metadata_field_name,
$index
);
if ( $result ) {
$processed_styles[] = $result;
}
}
} else {
$result = register_block_style_handle(
$metadata,
$metadata_field_name
);
if ( $result ) {
$processed_styles[] = $result;
}
}
$settings[ $settings_field_name ] = $processed_styles;
}
}
if ( ! empty( $metadata['blockHooks'] ) ) {
/**
* Map camelCased position string (from block.json) to snake_cased block type position.
*
* @var array
*/
$position_mappings = array(
'before' => 'before',
'after' => 'after',
'firstChild' => 'first_child',
'lastChild' => 'last_child',
);
$settings['block_hooks'] = array();
foreach ( $metadata['blockHooks'] as $anchor_block_name => $position ) {
// Avoid infinite recursion (hooking to itself).
if ( $metadata['name'] === $anchor_block_name ) {
_doing_it_wrong(
__METHOD__,
__( 'Cannot hook block to itself.' ),
'6.4.0'
);
continue;
}
if ( ! isset( $position_mappings[ $position ] ) ) {
continue;
}
$settings['block_hooks'][ $anchor_block_name ] = $position_mappings[ $position ];
}
}
/**
* Filters the settings determined from the block type metadata.
*
* @since 5.7.0
*
* @param array $settings Array of determined settings for registering a block type.
* @param array $metadata Metadata provided for registering a block type.
*/
$settings = apply_filters( 'block_type_metadata_settings', $settings, $metadata );
$metadata['name'] = ! empty( $settings['name'] ) ? $settings['name'] : $metadata['name'];
return WP_Block_Type_Registry::get_instance()->register(
$metadata['name'],
$settings
);
}
/**
* Registers a block type. The recommended way is to register a block type using
* the metadata stored in the `block.json` file.
*
* @since 5.0.0
* @since 5.8.0 First parameter now accepts a path to the `block.json` file.
*
* @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively
* a path to the JSON file with metadata definition for the block,
* or a path to the folder where the `block.json` file is located,
* or a complete WP_Block_Type instance.
* In case a WP_Block_Type is provided, the $args parameter will be ignored.
* @param array $args Optional. Array of block type arguments. Accepts any public property
* of `WP_Block_Type`. See WP_Block_Type::__construct() for information
* on accepted arguments. Default empty array.
*
* @return WP_Block_Type|false The registered block type on success, or false on failure.
*/
function register_block_type( $block_type, $args = array() ) {
if ( is_string( $block_type ) && file_exists( $block_type ) ) {
return register_block_type_from_metadata( $block_type, $args );
}
return WP_Block_Type_Registry::get_instance()->register( $block_type, $args );
}
/**
* Unregisters a block type.
*
* @since 5.0.0
*
* @param string|WP_Block_Type $name Block type name including namespace, or alternatively
* a complete WP_Block_Type instance.
* @return WP_Block_Type|false The unregistered block type on success, or false on failure.
*/
function unregister_block_type( $name ) {
return WP_Block_Type_Registry::get_instance()->unregister( $name );
}
/**
* Determines whether a post or content string has blocks.
*
* This test optimizes for performance rather than strict accuracy, detecting
* the pattern of a block but not validating its structure. For strict accuracy,
* you should use the block parser on post content.
*
* @since 5.0.0
*
* @see parse_blocks()
*
* @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
* Defaults to global $post.
* @return bool Whether the post has blocks.
*/
function has_blocks( $post = null ) {
if ( ! is_string( $post ) ) {
$wp_post = get_post( $post );
if ( ! $wp_post instanceof WP_Post ) {
return false;
}
$post = $wp_post->post_content;
}
return str_contains( (string) $post, '<!-- wp:' );
}
/**
* Determines whether a $post or a string contains a specific block type.
*
* This test optimizes for performance rather than strict accuracy, detecting
* whether the block type exists but not validating its structure and not checking
* synced patterns (formerly called reusable blocks). For strict accuracy,
* you should use the block parser on post content.
*
* @since 5.0.0
*
* @see parse_blocks()
*
* @param string $block_name Full block type to look for.
* @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object.
* Defaults to global $post.
* @return bool Whether the post content contains the specified block.
*/
function has_block( $block_name, $post = null ) {
if ( ! has_blocks( $post ) ) {
return false;
}
if ( ! is_string( $post ) ) {
$wp_post = get_post( $post );
if ( $wp_post instanceof WP_Post ) {
$post = $wp_post->post_content;
}
}
/*
* Normalize block name to include namespace, if provided as non-namespaced.
* This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by
* their serialized names.
*/
if ( ! str_contains( $block_name, '/' ) ) {
$block_name = 'core/' . $block_name;
}
// Test for existence of block by its fully qualified name.
$has_block = str_contains( $post, '<!-- wp:' . $block_name . ' ' );
if ( ! $has_block ) {
/*
* If the given block name would serialize to a different name, test for
* existence by the serialized form.
*/
$serialized_block_name = strip_core_block_namespace( $block_name );
if ( $serialized_block_name !== $block_name ) {
$has_block = str_contains( $post, '<!-- wp:' . $serialized_block_name . ' ' );
}
}
return $has_block;
}
/**
* Returns an array of the names of all registered dynamic block types.
*
* @since 5.0.0
*
* @return string[] Array of dynamic block names.
*/
function get_dynamic_block_names() {
$dynamic_block_names = array();
$block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
foreach ( $block_types as $block_type ) {
if ( $block_type->is_dynamic() ) {
$dynamic_block_names[] = $block_type->name;
}
}
return $dynamic_block_names;
}
/**
* Retrieves block types hooked into the given block, grouped by anchor block type and the relative position.
*
* @since 6.4.0
*
* @return array[] Array of block types grouped by anchor block type and the relative position.
*/
function get_hooked_blocks() {
$block_types = WP_Block_Type_Registry::get_instance()->get_all_registered();
$hooked_blocks = array();
foreach ( $block_types as $block_type ) {
if ( ! ( $block_type instanceof WP_Block_Type ) || ! is_array( $block_type->block_hooks ) ) {
continue;
}
foreach ( $block_type->block_hooks as $anchor_block_type => $relative_position ) {
if ( ! isset( $hooked_blocks[ $anchor_block_type ] ) ) {
$hooked_blocks[ $anchor_block_type ] = array();
}
if ( ! isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] ) ) {
$hooked_blocks[ $anchor_block_type ][ $relative_position ] = array();
}
$hooked_blocks[ $anchor_block_type ][ $relative_position ][] = $block_type->name;
}
}
return $hooked_blocks;
}
/**
* Conditionally returns the markup for a given hooked block.
*
* Accepts three arguments: A hooked block, its type, and a reference to an anchor block.
* If the anchor block has already been processed, and the given hooked block type is in the list
* of ignored hooked blocks, an empty string is returned.
*
* The hooked block type is specified separately as it's possible that a filter might've modified
* the hooked block such that `$hooked_block['blockName']` does no longer reflect the original type.
*
* This function is meant for internal use only.
*
* @since 6.5.0
* @access private
*
* @param array $hooked_block The hooked block, represented as a parsed block array.
* @param string $hooked_block_type The type of the hooked block. This could be different from
* $hooked_block['blockName'], as a filter might've modified the latter.
* @param array $anchor_block The anchor block, represented as a parsed block array.
* Passed by reference.
* @return string The markup for the given hooked block, or an empty string if the block is ignored.
*/
function get_hooked_block_markup( $hooked_block, $hooked_block_type, &$anchor_block ) {
if ( ! isset( $anchor_block['attrs']['metadata']['ignoredHookedBlocks'] ) ) {
$anchor_block['attrs']['metadata']['ignoredHookedBlocks'] = array();
}
if ( in_array( $hooked_block_type, $anchor_block['attrs']['metadata']['ignoredHookedBlocks'], true ) ) {
return '';
}
// The following is only needed for the REST API endpoint.
// However, its presence does not affect the frontend.
$anchor_block['attrs']['metadata']['ignoredHookedBlocks'][] = $hooked_block_type;
return serialize_block( $hooked_block );
}
/**
* Returns the markup for blocks hooked to the given anchor block in a specific relative position.
*
* @since 6.5.0
* @access private
*
* @param array $parsed_anchor_block The anchor block, in parsed block array format.
* @param string $relative_position The relative position of the hooked blocks.
* Can be one of 'before', 'after', 'first_child', or 'last_child'.
* @param array $hooked_blocks An array of hooked block types, grouped by anchor block and relative position.
* @param WP_Block_Template|array $context The block template, template part, or pattern that the anchor block belongs to.
* @return string
*/
function insert_hooked_blocks( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) {
$anchor_block_type = $parsed_anchor_block['blockName'];
$hooked_block_types = isset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] )
? $hooked_blocks[ $anchor_block_type ][ $relative_position ]
: array();
/**
* Filters the list of hooked block types for a given anchor block type and relative position.
*
* @since 6.4.0
*
* @param string[] $hooked_block_types The list of hooked block types.
* @param string $relative_position The relative position of the hooked blocks.
* Can be one of 'before', 'after', 'first_child', or 'last_child'.
* @param string $anchor_block_type The anchor block type.
* @param WP_Block_Template|WP_Post|array $context The block template, template part, `wp_navigation` post type,
* or pattern that the anchor block belongs to.
*/
$hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context );
$markup = '';
foreach ( $hooked_block_types as $hooked_block_type ) {
$parsed_hooked_block = array(
'blockName' => $hooked_block_type,
'attrs' => array(),
'innerBlocks' => array(),
'innerContent' => array(),
);
/**
* Filters the parsed block array for a given hooked block.
*
* The dynamic portion of the hook name, `$hooked_block_type`, refers to the block type name of the specific hooked block.
*
* @since 6.5.0
*
* @param array $parsed_hooked_block The parsed block array for the given hooked block type.
* @param string $relative_position The relative position of the hooked block.
* @param array $parsed_anchor_block The anchor block, in parsed block array format.
* @param WP_Block_Template|WP_Post|array $context The block template, template part, `wp_navigation` post type,
* or pattern that the anchor block belongs to.
*/
$parsed_hooked_block = apply_filters( "hooked_block_{$hooked_block_type}", $parsed_hooked_block, $relative_position, $parsed_anchor_block, $context );
// It's possible that the `hooked_block_{$hooked_block_type}` filter returned a block of a different type,
// so we need to pass the original $hooked_block_type as well.
$markup .= get_hooked_block_markup( $parsed_hooked_block, $hooked_block_type, $parsed_anchor_block );
}
return $markup;
}
/**
* Returns a function that injects the theme attribute into, and hooked blocks before, a given block.
*
* The returned function can be used as `$pre_callback` argument to `traverse_and_serialize_block(s)`,
* where it will inject the `theme` attribute into all Template Part blocks, and prepend the markup for
* any blocks hooked `before` the given block and as its parent's `first_child`, respectively.
*
* This function is meant for internal use only.
*
* @since 6.4.0
* @access private
*
* @param array $hooked_blocks An array of blocks hooked to another given block.
* @param WP_Block_Template|WP_Post|array $context A block template, template part, `wp_navigation` post object,
* or pattern that the blocks belong to.
* @return callable A function that returns the serialized markup for the given block,
* including the markup for any hooked blocks before it.
*/
function make_before_block_visitor( $hooked_blocks, $context ) {
/**
* Injects hooked blocks before the given block, injects the `theme` attribute into Template Part blocks, and returns the serialized markup.
*
* If the current block is a Template Part block, inject the `theme` attribute.
* Furthermore, prepend the markup for any blocks hooked `before` the given block and as its parent's
* `first_child`, respectively, to the serialized markup for the given block.
*
* @param array $block The block to inject the theme attribute into, and hooked blocks before. Passed by reference.
* @param array $parent_block The parent block of the given block. Passed by reference. Default null.
* @param array $prev The previous sibling block of the given block. Default null.
* @return string The serialized markup for the given block, with the markup for any hooked blocks prepended to it.
*/
return function ( &$block, &$parent_block = null, $prev = null ) use ( $hooked_blocks, $context ) {
_inject_theme_attribute_in_template_part_block( $block );
$markup = '';
if ( $parent_block && ! $prev ) {
// Candidate for first-child insertion.
$markup .= insert_hooked_blocks( $parent_block, 'first_child', $hooked_blocks, $context );
}
$markup .= insert_hooked_blocks( $block, 'before', $hooked_blocks, $context );
return $markup;
};
}
/**
* Returns a function that injects the hooked blocks after a given block.
*
* The returned function can be used as `$post_callback` argument to `traverse_and_serialize_block(s)`,
* where it will append the markup for any blocks hooked `after` the given block and as its parent's