| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Functions related to registering and parsing blocks. 4 * 5 * @package WordPress 6 * @subpackage Blocks 7 * @since 5.0.0 8 */ 9 10 /** 11 * Removes the block asset's path prefix if provided. 12 * 13 * @since 5.5.0 14 * 15 * @param string $asset_handle_or_path Asset handle or prefixed path. 16 * @return string Path without the prefix or the original value. 17 */ 18 function remove_block_asset_path_prefix( $asset_handle_or_path ) { 19 $path_prefix = 'file:'; 20 if ( ! str_starts_with( $asset_handle_or_path, $path_prefix ) ) { 21 return $asset_handle_or_path; 22 } 23 $path = substr( 24 $asset_handle_or_path, 25 strlen( $path_prefix ) 26 ); 27 if ( str_starts_with( $path, './' ) ) { 28 $path = substr( $path, 2 ); 29 } 30 return $path; 31 } 32 33 /** 34 * Generates the name for an asset based on the name of the block 35 * and the field name provided. 36 * 37 * @since 5.5.0 38 * @since 6.1.0 Added `$index` parameter. 39 * @since 6.5.0 Added support for `viewScriptModule` field. 40 * 41 * @param string $block_name Name of the block. 42 * @param string $field_name Name of the metadata field. 43 * @param int $index Optional. Index of the asset when multiple items passed. 44 * Default 0. 45 * @return string Generated asset name for the block's field. 46 * 47 * @phpstan-param non-falsy-string $block_name 48 * @phpstan-param 'editorScript'|'editorStyle'|'script'|'style'|'viewScript'|'viewScriptModule'|'viewStyle' $field_name 49 * @phpstan-param int<0, max> $index 50 * @phpstan-return non-falsy-string 51 */ 52 function generate_block_asset_handle( $block_name, $field_name, $index = 0 ) { 53 if ( str_starts_with( $block_name, 'core/' ) ) { 54 $asset_handle = str_replace( 'core/', 'wp-block-', $block_name ); 55 if ( str_starts_with( $field_name, 'editor' ) ) { 56 $asset_handle .= '-editor'; 57 } 58 if ( str_starts_with( $field_name, 'view' ) ) { 59 $asset_handle .= '-view'; 60 } 61 if ( str_ends_with( strtolower( $field_name ), 'scriptmodule' ) ) { 62 $asset_handle .= '-script-module'; 63 } 64 if ( $index > 0 ) { 65 $asset_handle .= '-' . ( $index + 1 ); 66 } 67 return $asset_handle; 68 } 69 70 $field_mappings = array( 71 'editorScript' => 'editor-script', 72 'editorStyle' => 'editor-style', 73 'script' => 'script', 74 'style' => 'style', 75 'viewScript' => 'view-script', 76 'viewScriptModule' => 'view-script-module', 77 'viewStyle' => 'view-style', 78 ); 79 $asset_handle = str_replace( '/', '-', $block_name ) . 80 '-' . $field_mappings[ $field_name ]; 81 if ( $index > 0 ) { 82 $asset_handle .= '-' . ( $index + 1 ); 83 } 84 return $asset_handle; 85 } 86 87 /** 88 * Gets the URL to a block asset. 89 * 90 * @since 6.4.0 91 * 92 * @param string $path A normalized path to a block asset. 93 * @return string|false The URL to the block asset or false on failure. 94 * 95 * @phpstan-return non-falsy-string|false 96 */ 97 function get_block_asset_url( $path ) { 98 if ( empty( $path ) ) { 99 return false; 100 } 101 102 // Path needs to be normalized to work in Windows env. 103 static $wpinc_path_norm = ''; 104 if ( ! $wpinc_path_norm ) { 105 $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) ); 106 } 107 108 if ( str_starts_with( $path, $wpinc_path_norm ) ) { 109 return includes_url( str_replace( $wpinc_path_norm, '', $path ) ); 110 } 111 112 /** @var array<string, string> $template_paths_norm */ 113 static $template_paths_norm = array(); 114 115 $template = get_template(); 116 if ( ! isset( $template_paths_norm[ $template ] ) ) { 117 $template_paths_norm[ $template ] = wp_normalize_path( realpath( get_template_directory() ) ); 118 } 119 120 if ( str_starts_with( $path, trailingslashit( $template_paths_norm[ $template ] ) ) ) { 121 return get_theme_file_uri( str_replace( $template_paths_norm[ $template ], '', $path ) ); 122 } 123 124 if ( is_child_theme() ) { 125 $stylesheet = get_stylesheet(); 126 if ( ! isset( $template_paths_norm[ $stylesheet ] ) ) { 127 $template_paths_norm[ $stylesheet ] = wp_normalize_path( realpath( get_stylesheet_directory() ) ); 128 } 129 130 if ( str_starts_with( $path, trailingslashit( $template_paths_norm[ $stylesheet ] ) ) ) { 131 return get_theme_file_uri( str_replace( $template_paths_norm[ $stylesheet ], '', $path ) ); 132 } 133 } 134 135 return plugins_url( basename( $path ), $path ); 136 } 137 138 /** 139 * Finds a script module ID for the selected block metadata field. 140 * 141 * Detects when a path to a file was provided and optionally finds a 142 * corresponding asset file with details necessary to register the script 143 * module with an automatically generated module ID. It returns the 144 * unprocessed script module ID otherwise. 145 * 146 * @since 6.5.0 147 * 148 * @param array $metadata Block metadata. 149 * @param string $field_name Field name to pick from metadata. 150 * @param int $index Optional. Index of the script module ID to register when multiple 151 * items passed. Default 0. 152 * @return string|false Script module ID or false on failure. 153 * 154 * @phpstan-param array{ 155 * name?: non-falsy-string, 156 * file: non-falsy-string|null, 157 * version?: string, 158 * supports?: array{ 159 * interactivity?: bool|array{interactive?: bool, clientNavigation?: bool, ...}, 160 * ... 161 * }, 162 * viewScriptModule?: string|list<string>, 163 * ... 164 * } $metadata 165 * @phpstan-param 'viewScriptModule' $field_name 166 * @phpstan-param int<0, max> $index 167 * @phpstan-return non-falsy-string|false 168 */ 169 function register_block_script_module_id( $metadata, $field_name, $index = 0 ) { 170 if ( empty( $metadata[ $field_name ] ) ) { 171 return false; 172 } 173 174 $module_id = $metadata[ $field_name ]; 175 if ( is_array( $module_id ) ) { 176 if ( empty( $module_id[ $index ] ) ) { 177 return false; 178 } 179 $module_id = $module_id[ $index ]; 180 } 181 182 $module_path = remove_block_asset_path_prefix( $module_id ); 183 if ( $module_id === $module_path ) { 184 return $module_id; 185 } 186 187 $path = dirname( $metadata['file'] ); 188 $module_asset_raw_path = $path . '/' . substr_replace( $module_path, '.asset.php', - strlen( '.js' ) ); 189 $module_id = generate_block_asset_handle( $metadata['name'], $field_name, $index ); 190 $module_asset_path = wp_normalize_path( 191 realpath( $module_asset_raw_path ) 192 ); 193 194 $module_path_norm = wp_normalize_path( realpath( $path . '/' . $module_path ) ); 195 $module_uri = get_block_asset_url( $module_path_norm ); 196 197 /** @var array{ dependencies?: list<non-falsy-string|array{id: non-falsy-string, import?: 'static'|'dynamic'}>, version?: string|false|null, ... } $module_asset */ 198 $module_asset = ! empty( $module_asset_path ) ? require $module_asset_path : array(); 199 $module_dependencies = $module_asset['dependencies'] ?? array(); 200 $block_version = $metadata['version'] ?? false; 201 $module_version = $module_asset['version'] ?? $block_version; 202 203 $supports_interactivity_true = isset( $metadata['supports']['interactivity'] ) && true === $metadata['supports']['interactivity']; 204 $is_interactive = $supports_interactivity_true || ( isset( $metadata['supports']['interactivity']['interactive'] ) && true === $metadata['supports']['interactivity']['interactive'] ); 205 $supports_client_navigation = $supports_interactivity_true || ( isset( $metadata['supports']['interactivity']['clientNavigation'] ) && true === $metadata['supports']['interactivity']['clientNavigation'] ); 206 207 $args = array(); 208 209 // Blocks using the Interactivity API are server-side rendered, so they are 210 // by design not in the critical rendering path and should be deprioritized. 211 if ( $is_interactive ) { 212 $args['fetchpriority'] = 'low'; 213 $args['in_footer'] = true; 214 } 215 216 // Blocks using the Interactivity API that support client-side navigation 217 // must be marked as such in their script modules. 218 if ( $is_interactive && $supports_client_navigation ) { 219 wp_interactivity()->add_client_navigation_support_to_script_module( $module_id ); 220 } 221 222 wp_register_script_module( 223 $module_id, 224 $module_uri, 225 $module_dependencies, 226 $module_version, 227 $args 228 ); 229 230 return $module_id; 231 } 232 233 /** 234 * Finds a script handle for the selected block metadata field. 235 * 236 * Detects when a path to a file was provided and optionally finds a 237 * corresponding asset file with details necessary to register the script. The 238 * handle is taken from the asset file when it provides one, and is otherwise 239 * generated automatically. It returns the unprocessed script handle when a 240 * handle rather than a path was given. 241 * 242 * @since 5.5.0 243 * @since 6.1.0 Added `$index` parameter. 244 * @since 6.5.0 The asset file is optional. Added script handle support in the asset file. 245 * 246 * @param array $metadata Block metadata. 247 * @param string $field_name Field name to pick from metadata. 248 * @param int $index Optional. Index of the script to register when multiple items passed. 249 * Default 0. 250 * @return string|false Script handle provided directly or created through 251 * script's registration, or false on failure. 252 * 253 * @phpstan-param array{ 254 * name?: non-falsy-string, 255 * file: non-falsy-string|null, 256 * version?: string, 257 * textdomain?: string, 258 * editorScript?: string|list<string>, 259 * script?: string|list<string>, 260 * viewScript?: string|list<string>, 261 * ... 262 * } $metadata 263 * @phpstan-param 'editorScript'|'script'|'viewScript' $field_name 264 * @phpstan-param int<0, max> $index 265 * @phpstan-return non-falsy-string|false 266 */ 267 function register_block_script_handle( $metadata, $field_name, $index = 0 ) { 268 if ( empty( $metadata[ $field_name ] ) ) { 269 return false; 270 } 271 272 $script_handle_or_path = $metadata[ $field_name ]; 273 if ( is_array( $script_handle_or_path ) ) { 274 if ( empty( $script_handle_or_path[ $index ] ) ) { 275 return false; 276 } 277 $script_handle_or_path = $script_handle_or_path[ $index ]; 278 } 279 280 $script_path = remove_block_asset_path_prefix( $script_handle_or_path ); 281 if ( $script_handle_or_path === $script_path ) { 282 return $script_handle_or_path; 283 } 284 285 $path = dirname( $metadata['file'] ); 286 $script_asset_raw_path = $path . '/' . substr_replace( $script_path, '.asset.php', - strlen( '.js' ) ); 287 $script_asset_path = wp_normalize_path( 288 realpath( $script_asset_raw_path ) 289 ); 290 291 // Asset file for blocks is optional. See https://core.trac.wordpress.org/ticket/60460. 292 /** @var array{ handle?: non-falsy-string, dependencies?: list<non-falsy-string>, version?: string|false|null, ... } $script_asset */ 293 $script_asset = ! empty( $script_asset_path ) ? require $script_asset_path : array(); 294 $script_handle = $script_asset['handle'] ?? 295 generate_block_asset_handle( $metadata['name'], $field_name, $index ); 296 if ( wp_script_is( $script_handle, 'registered' ) ) { 297 return $script_handle; 298 } 299 300 $script_path_norm = wp_normalize_path( realpath( $path . '/' . $script_path ) ); 301 $script_uri = get_block_asset_url( $script_path_norm ); 302 $script_dependencies = $script_asset['dependencies'] ?? array(); 303 $block_version = $metadata['version'] ?? false; 304 $script_version = $script_asset['version'] ?? $block_version; 305 $script_args = array(); 306 if ( 'viewScript' === $field_name && $script_uri ) { 307 $script_args['strategy'] = 'defer'; 308 } 309 310 $result = wp_register_script( 311 $script_handle, 312 $script_uri, 313 $script_dependencies, 314 $script_version, 315 $script_args 316 ); 317 if ( ! $result ) { 318 return false; 319 } 320 321 if ( ! empty( $metadata['textdomain'] ) && in_array( 'wp-i18n', $script_dependencies, true ) ) { 322 wp_set_script_translations( $script_handle, $metadata['textdomain'] ); 323 } 324 325 return $script_handle; 326 } 327 328 /** 329 * Finds a style handle for the block metadata field. 330 * 331 * Detects when a path to a file was provided and registers the style under an 332 * automatically generated handle name. It returns the unprocessed style handle 333 * otherwise, except for the first style of a core block, which is instead 334 * registered from the block's own stylesheet when separate core block assets 335 * are loaded. Core blocks accept only handles, not paths. 336 * 337 * @since 5.5.0 338 * @since 6.1.0 Added `$index` parameter. 339 * 340 * @param array $metadata Block metadata. 341 * @param string $field_name Field name to pick from metadata. 342 * @param int $index Optional. Index of the style to register when multiple items passed. 343 * Default 0. 344 * @return string|false Style handle provided directly or created through 345 * style's registration, or false on failure. 346 * 347 * @phpstan-param array{ 348 * name?: non-falsy-string, 349 * file: non-falsy-string|null, 350 * version?: string, 351 * editorStyle?: string|list<string>, 352 * style?: string|list<string>, 353 * viewStyle?: string|list<string>, 354 * ... 355 * } $metadata 356 * @phpstan-param 'editorStyle'|'style'|'viewStyle' $field_name 357 * @phpstan-param int<0, max> $index 358 * @phpstan-return non-falsy-string|false 359 */ 360 function register_block_style_handle( $metadata, $field_name, $index = 0 ) { 361 if ( empty( $metadata[ $field_name ] ) ) { 362 return false; 363 } 364 365 $style_handle = $metadata[ $field_name ]; 366 if ( is_array( $style_handle ) ) { 367 if ( empty( $style_handle[ $index ] ) ) { 368 return false; 369 } 370 $style_handle = $style_handle[ $index ]; 371 } 372 373 $style_handle_name = generate_block_asset_handle( $metadata['name'], $field_name, $index ); 374 // If the style handle is already registered, skip re-registering. 375 if ( wp_style_is( $style_handle_name, 'registered' ) ) { 376 return $style_handle_name; 377 } 378 379 static $wpinc_path_norm = ''; 380 if ( ! $wpinc_path_norm ) { 381 $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) ); 382 } 383 384 $is_core_block = isset( $metadata['file'] ) && str_starts_with( $metadata['file'], $wpinc_path_norm ); 385 // Skip registering individual styles for each core block when a bundled version provided. 386 if ( $is_core_block && ! wp_should_load_separate_core_block_assets() ) { 387 return false; 388 } 389 390 $style_path = remove_block_asset_path_prefix( $style_handle ); 391 $is_style_handle = $style_handle === $style_path; 392 // Allow only passing style handles for core blocks. 393 if ( $is_core_block && ! $is_style_handle ) { 394 return false; 395 } 396 // Return the style handle unless it's the first item for every core block that requires special treatment. 397 if ( $is_style_handle && ! ( $is_core_block && 0 === $index ) ) { 398 return $style_handle; 399 } 400 401 // Check whether styles should have a ".min" suffix or not. 402 $suffix = SCRIPT_DEBUG ? '' : '.min'; 403 if ( $is_core_block ) { 404 $style_path = ( 'editorStyle' === $field_name ) ? "editor{$suffix}.css" : "style{$suffix}.css"; 405 } 406 407 $style_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $style_path ) ); 408 $style_uri = get_block_asset_url( $style_path_norm ); 409 410 $block_version = ! $is_core_block && isset( $metadata['version'] ) ? $metadata['version'] : false; 411 $version = $style_path_norm && defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? filemtime( $style_path_norm ) : $block_version; 412 $result = wp_register_style( 413 $style_handle_name, 414 $style_uri, 415 array(), 416 $version 417 ); 418 if ( ! $result ) { 419 return false; 420 } 421 422 if ( $style_uri ) { 423 wp_style_add_data( $style_handle_name, 'path', $style_path_norm ); 424 425 if ( $is_core_block ) { 426 $rtl_file = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $style_path_norm ); 427 } else { 428 $rtl_file = str_replace( '.css', '-rtl.css', $style_path_norm ); 429 } 430 431 if ( is_rtl() && file_exists( $rtl_file ) ) { 432 wp_style_add_data( $style_handle_name, 'rtl', 'replace' ); 433 wp_style_add_data( $style_handle_name, 'suffix', $suffix ); 434 wp_style_add_data( $style_handle_name, 'path', $rtl_file ); 435 } 436 } 437 438 return $style_handle_name; 439 } 440 441 /** 442 * Gets i18n schema for block's metadata read from `block.json` file. 443 * 444 * @since 5.9.0 445 * 446 * @return object The schema for block's metadata. 447 */ 448 function get_block_metadata_i18n_schema() { 449 static $i18n_block_schema; 450 451 if ( ! isset( $i18n_block_schema ) ) { 452 $i18n_block_schema = wp_json_file_decode( __DIR__ . '/block-i18n.json' ); 453 } 454 455 return $i18n_block_schema; 456 } 457 458 /** 459 * Registers all block types from a block metadata collection. 460 * 461 * This can either reference a previously registered metadata collection or, if the `$manifest` parameter is provided, 462 * register the metadata collection directly within the same function call. 463 * 464 * @since 6.8.0 465 * @see wp_register_block_metadata_collection() 466 * @see register_block_type_from_metadata() 467 * 468 * @param string $path The absolute base path for the collection ( e.g., WP_PLUGIN_DIR . '/my-plugin/blocks/' ). 469 * @param string $manifest Optional. The absolute path to the manifest file containing the metadata collection, in 470 * order to register the collection. If this parameter is not provided, the `$path` parameter 471 * must reference a previously registered block metadata collection. 472 */ 473 function wp_register_block_types_from_metadata_collection( $path, $manifest = '' ) { 474 if ( $manifest ) { 475 wp_register_block_metadata_collection( $path, $manifest ); 476 } 477 478 $block_metadata_files = WP_Block_Metadata_Registry::get_collection_block_metadata_files( $path ); 479 foreach ( $block_metadata_files as $block_metadata_file ) { 480 register_block_type_from_metadata( $block_metadata_file ); 481 } 482 } 483 484 /** 485 * Registers a block metadata collection. 486 * 487 * This function allows core and third-party plugins to register their block metadata 488 * collections in a centralized location. Registering collections can improve performance 489 * by avoiding multiple reads from the filesystem and parsing JSON. 490 * 491 * @since 6.7.0 492 * 493 * @param string $path The base path in which block files for the collection reside. 494 * @param string $manifest The path to the manifest file for the collection. 495 */ 496 function wp_register_block_metadata_collection( $path, $manifest ) { 497 WP_Block_Metadata_Registry::register_collection( $path, $manifest ); 498 } 499 500 /** 501 * Registers a block type from the metadata stored in the `block.json` file. 502 * 503 * @since 5.5.0 504 * @since 5.7.0 Added support for `textdomain` field and i18n handling for all translatable fields. 505 * @since 5.9.0 Added support for `variations` and `viewScript` fields. 506 * @since 6.1.0 Added support for `render` field. 507 * @since 6.3.0 Added `selectors` field. 508 * @since 6.4.0 Added support for `blockHooks` field. 509 * @since 6.5.0 Added support for `allowedBlocks`, `viewScriptModule`, and `viewStyle` fields. 510 * @since 6.7.0 Allow PHP filename as `variations` argument. 511 * 512 * @param string $file_or_folder Path to the JSON file with metadata definition for 513 * the block or path to the folder where the `block.json` file is located. 514 * If providing the path to a JSON file, the filename must end with `block.json`. 515 * @param array $args Optional. Array of block type arguments. Accepts any public property 516 * of `WP_Block_Type`. See WP_Block_Type::__construct() for information 517 * on accepted arguments. Default empty array. 518 * @return WP_Block_Type|false The registered block type on success, or false on failure. 519 */ 520 function register_block_type_from_metadata( $file_or_folder, $args = array() ) { 521 /* 522 * Get an array of metadata from a PHP file. 523 * This improves performance for core blocks as it's only necessary to read a single PHP file 524 * instead of reading a JSON file per-block, and then decoding from JSON to PHP. 525 * Using a static variable ensures that the metadata is only read once per request. 526 */ 527 528 $file_or_folder = wp_normalize_path( $file_or_folder ); 529 530 $metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ? 531 trailingslashit( $file_or_folder ) . 'block.json' : 532 $file_or_folder; 533 534 $is_core_block = str_starts_with( $file_or_folder, wp_normalize_path( ABSPATH . WPINC ) ); 535 $metadata_file_exists = $is_core_block || file_exists( $metadata_file ); 536 $registry_metadata = WP_Block_Metadata_Registry::get_metadata( $file_or_folder ); 537 538 if ( $registry_metadata ) { 539 $metadata = $registry_metadata; 540 } elseif ( $metadata_file_exists ) { 541 $metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) ); 542 } else { 543 $metadata = array(); 544 } 545 546 if ( ! is_array( $metadata ) || ( empty( $metadata['name'] ) && empty( $args['name'] ) ) ) { 547 return false; 548 } 549 550 $metadata['file'] = $metadata_file_exists ? wp_normalize_path( realpath( $metadata_file ) ) : null; 551 552 /** 553 * Filters the metadata provided for registering a block type. 554 * 555 * @since 5.7.0 556 * 557 * @param array $metadata Metadata for registering a block type. 558 */ 559 $metadata = apply_filters( 'block_type_metadata', $metadata ); 560 561 // Add `style` and `editor_style` for core blocks if missing. 562 if ( ! empty( $metadata['name'] ) && str_starts_with( $metadata['name'], 'core/' ) ) { 563 $block_name = str_replace( 'core/', '', $metadata['name'] ); 564 565 if ( ! isset( $metadata['style'] ) ) { 566 $metadata['style'] = "wp-block-$block_name"; 567 } 568 if ( current_theme_supports( 'wp-block-styles' ) && wp_should_load_separate_core_block_assets() ) { 569 $metadata['style'] = (array) $metadata['style']; 570 $metadata['style'][] = "wp-block-{$block_name}-theme"; 571 } 572 if ( ! isset( $metadata['editorStyle'] ) ) { 573 $metadata['editorStyle'] = "wp-block-{$block_name}-editor"; 574 } 575 } 576 577 $settings = array(); 578 $property_mappings = array( 579 'apiVersion' => 'api_version', 580 'name' => 'name', 581 'title' => 'title', 582 'category' => 'category', 583 'parent' => 'parent', 584 'ancestor' => 'ancestor', 585 'icon' => 'icon', 586 'description' => 'description', 587 'keywords' => 'keywords', 588 'attributes' => 'attributes', 589 'providesContext' => 'provides_context', 590 'usesContext' => 'uses_context', 591 'selectors' => 'selectors', 592 'supports' => 'supports', 593 'styles' => 'styles', 594 'variations' => 'variations', 595 'example' => 'example', 596 'allowedBlocks' => 'allowed_blocks', 597 ); 598 $textdomain = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null; 599 $i18n_schema = get_block_metadata_i18n_schema(); 600 601 foreach ( $property_mappings as $key => $mapped_key ) { 602 if ( isset( $metadata[ $key ] ) ) { 603 $settings[ $mapped_key ] = $metadata[ $key ]; 604 if ( $metadata_file_exists && $textdomain && isset( $i18n_schema->$key ) ) { 605 $settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain ); 606 } 607 } 608 } 609 610 if ( ! empty( $metadata['render'] ) ) { 611 $template_path = wp_normalize_path( 612 realpath( 613 dirname( $metadata['file'] ) . '/' . 614 remove_block_asset_path_prefix( $metadata['render'] ) 615 ) 616 ); 617 if ( $template_path ) { 618 /** 619 * Renders the block on the server. 620 * 621 * @since 6.1.0 622 * 623 * @param array $attributes Block attributes. 624 * @param string $content Block default content. 625 * @param WP_Block $block Block instance. 626 * @return string Returns the block content. 627 */ 628 $settings['render_callback'] = static function ( $attributes, $content, $block ) use ( $template_path ) { 629 ob_start(); 630 require $template_path; 631 return ob_get_clean(); 632 }; 633 } 634 } 635 636 // If `variations` is a string, it's the name of a PHP file that 637 // generates the variations. 638 if ( ! empty( $metadata['variations'] ) && is_string( $metadata['variations'] ) ) { 639 $variations_path = wp_normalize_path( 640 realpath( 641 dirname( $metadata['file'] ) . '/' . 642 remove_block_asset_path_prefix( $metadata['variations'] ) 643 ) 644 ); 645 if ( $variations_path ) { 646 /** 647 * Generates the list of block variations. 648 * 649 * @since 6.7.0 650 * 651 * @return string Returns the list of block variations. 652 */ 653 $settings['variation_callback'] = static function () use ( $variations_path ) { 654 $variations = require $variations_path; 655 return $variations; 656 }; 657 // The block instance's `variations` field is only allowed to be an array 658 // (of known block variations). We unset it so that the block instance will 659 // provide a getter that returns the result of the `variation_callback` instead. 660 unset( $settings['variations'] ); 661 } 662 } 663 664 $settings = array_merge( $settings, $args ); 665 666 $script_fields = array( 667 'editorScript' => 'editor_script_handles', 668 'script' => 'script_handles', 669 'viewScript' => 'view_script_handles', 670 ); 671 foreach ( $script_fields as $metadata_field_name => $settings_field_name ) { 672 if ( ! empty( $settings[ $metadata_field_name ] ) ) { 673 $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ]; 674 } 675 if ( ! empty( $metadata[ $metadata_field_name ] ) ) { 676 $scripts = $metadata[ $metadata_field_name ]; 677 $processed_scripts = array(); 678 if ( is_array( $scripts ) ) { 679 for ( $index = 0, $length = count( $scripts ); $index < $length; $index++ ) { 680 $result = register_block_script_handle( 681 $metadata, 682 $metadata_field_name, 683 $index 684 ); 685 if ( $result ) { 686 $processed_scripts[] = $result; 687 } 688 } 689 } else { 690 $result = register_block_script_handle( 691 $metadata, 692 $metadata_field_name 693 ); 694 if ( $result ) { 695 $processed_scripts[] = $result; 696 } 697 } 698 $settings[ $settings_field_name ] = $processed_scripts; 699 } 700 } 701 702 $module_fields = array( 703 'viewScriptModule' => 'view_script_module_ids', 704 ); 705 foreach ( $module_fields as $metadata_field_name => $settings_field_name ) { 706 if ( ! empty( $settings[ $metadata_field_name ] ) ) { 707 $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ]; 708 } 709 if ( ! empty( $metadata[ $metadata_field_name ] ) ) { 710 $modules = $metadata[ $metadata_field_name ]; 711 $processed_modules = array(); 712 if ( is_array( $modules ) ) { 713 for ( $index = 0, $length = count( $modules ); $index < $length; $index++ ) { 714 $result = register_block_script_module_id( 715 $metadata, 716 $metadata_field_name, 717 $index 718 ); 719 if ( $result ) { 720 $processed_modules[] = $result; 721 } 722 } 723 } else { 724 $result = register_block_script_module_id( 725 $metadata, 726 $metadata_field_name 727 ); 728 if ( $result ) { 729 $processed_modules[] = $result; 730 } 731 } 732 $settings[ $settings_field_name ] = $processed_modules; 733 } 734 } 735 736 $style_fields = array( 737 'editorStyle' => 'editor_style_handles', 738 'style' => 'style_handles', 739 'viewStyle' => 'view_style_handles', 740 ); 741 foreach ( $style_fields as $metadata_field_name => $settings_field_name ) { 742 if ( ! empty( $settings[ $metadata_field_name ] ) ) { 743 $metadata[ $metadata_field_name ] = $settings[ $metadata_field_name ]; 744 } 745 if ( ! empty( $metadata[ $metadata_field_name ] ) ) { 746 $styles = $metadata[ $metadata_field_name ]; 747 $processed_styles = array(); 748 if ( is_array( $styles ) ) { 749 for ( $index = 0, $length = count( $styles ); $index < $length; $index++ ) { 750 $result = register_block_style_handle( 751 $metadata, 752 $metadata_field_name, 753 $index 754 ); 755 if ( $result ) { 756 $processed_styles[] = $result; 757 } 758 } 759 } else { 760 $result = register_block_style_handle( 761 $metadata, 762 $metadata_field_name 763 ); 764 if ( $result ) { 765 $processed_styles[] = $result; 766 } 767 } 768 $settings[ $settings_field_name ] = $processed_styles; 769 } 770 } 771 772 if ( ! empty( $metadata['blockHooks'] ) ) { 773 /** 774 * Map camelCased position string (from block.json) to snake_cased block type position. 775 * 776 * @var array 777 */ 778 $position_mappings = array( 779 'before' => 'before', 780 'after' => 'after', 781 'firstChild' => 'first_child', 782 'lastChild' => 'last_child', 783 ); 784 785 $settings['block_hooks'] = array(); 786 foreach ( $metadata['blockHooks'] as $anchor_block_name => $position ) { 787 // Avoid infinite recursion (hooking to itself). 788 if ( $metadata['name'] === $anchor_block_name ) { 789 _doing_it_wrong( 790 __METHOD__, 791 __( 'Cannot hook block to itself.' ), 792 '6.4.0' 793 ); 794 continue; 795 } 796 797 if ( ! isset( $position_mappings[ $position ] ) ) { 798 continue; 799 } 800 801 $settings['block_hooks'][ $anchor_block_name ] = $position_mappings[ $position ]; 802 } 803 } 804 805 /** 806 * Filters the settings determined from the block type metadata. 807 * 808 * @since 5.7.0 809 * 810 * @param array $settings Array of determined settings for registering a block type. 811 * @param array $metadata Metadata provided for registering a block type. 812 */ 813 $settings = apply_filters( 'block_type_metadata_settings', $settings, $metadata ); 814 815 $metadata['name'] = ! empty( $settings['name'] ) ? $settings['name'] : $metadata['name']; 816 817 return WP_Block_Type_Registry::get_instance()->register( 818 $metadata['name'], 819 $settings 820 ); 821 } 822 823 /** 824 * Registers a block type. The recommended way is to register a block type using 825 * the metadata stored in the `block.json` file. 826 * 827 * @since 5.0.0 828 * @since 5.8.0 First parameter now accepts a path to the `block.json` file. 829 * 830 * @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively 831 * a path to the JSON file with metadata definition for the block, 832 * or a path to the folder where the `block.json` file is located, 833 * or a complete WP_Block_Type instance. 834 * In case a WP_Block_Type is provided, the $args parameter will be ignored. 835 * @param array $args Optional. Array of block type arguments. Accepts any public property 836 * of `WP_Block_Type`. See WP_Block_Type::__construct() for information 837 * on accepted arguments. Default empty array. 838 * 839 * @return WP_Block_Type|false The registered block type on success, or false on failure. 840 */ 841 function register_block_type( $block_type, $args = array() ) { 842 if ( is_string( $block_type ) && file_exists( $block_type ) ) { 843 return register_block_type_from_metadata( $block_type, $args ); 844 } 845 846 /** @var (lowercase-string&non-falsy-string)|WP_Block_Type $block_type A string that is not a path to block metadata should be a block type name. */ 847 return WP_Block_Type_Registry::get_instance()->register( $block_type, $args ); 848 } 849 850 /** 851 * Unregisters a block type. 852 * 853 * @since 5.0.0 854 * 855 * @param string|WP_Block_Type $name Block type name including namespace, or alternatively 856 * a complete WP_Block_Type instance. 857 * @return WP_Block_Type|false The unregistered block type on success, or false on failure. 858 */ 859 function unregister_block_type( $name ) { 860 return WP_Block_Type_Registry::get_instance()->unregister( $name ); 861 } 862 863 /** 864 * Determines whether a post or content string has blocks. 865 * 866 * This test optimizes for performance rather than strict accuracy, detecting 867 * the pattern of a block but not validating its structure. For strict accuracy, 868 * you should use the block parser on post content. 869 * 870 * @since 5.0.0 871 * 872 * @see parse_blocks() 873 * 874 * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. 875 * Defaults to global $post. 876 * @return bool Whether the post has blocks. 877 */ 878 function has_blocks( $post = null ) { 879 if ( ! is_string( $post ) ) { 880 $wp_post = get_post( $post ); 881 882 if ( ! $wp_post instanceof WP_Post ) { 883 return false; 884 } 885 886 $post = $wp_post->post_content; 887 } 888 889 return str_contains( (string) $post, '<!-- wp:' ); 890 } 891 892 /** 893 * Determines whether a $post or a string contains a specific block type. 894 * 895 * This test optimizes for performance rather than strict accuracy, detecting 896 * whether the block type exists but not validating its structure and not checking 897 * synced patterns (formerly called reusable blocks). For strict accuracy, 898 * you should use the block parser on post content. 899 * 900 * @since 5.0.0 901 * 902 * @see parse_blocks() 903 * 904 * @param string $block_name Full block type to look for. 905 * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. 906 * Defaults to global $post. 907 * @return bool Whether the post content contains the specified block. 908 */ 909 function has_block( $block_name, $post = null ) { 910 if ( ! has_blocks( $post ) ) { 911 return false; 912 } 913 914 if ( ! is_string( $post ) ) { 915 $wp_post = get_post( $post ); 916 if ( $wp_post instanceof WP_Post ) { 917 $post = $wp_post->post_content; 918 } 919 } 920 921 /* 922 * Normalize block name to include namespace, if provided as non-namespaced. 923 * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by 924 * their serialized names. 925 */ 926 if ( ! str_contains( $block_name, '/' ) ) { 927 $block_name = 'core/' . $block_name; 928 } 929 930 // Test for existence of block by its fully qualified name. 931 $has_block = str_contains( $post, '<!-- wp:' . $block_name . ' ' ); 932 933 if ( ! $has_block ) { 934 /* 935 * If the given block name would serialize to a different name, test for 936 * existence by the serialized form. 937 */ 938 $serialized_block_name = strip_core_block_namespace( $block_name ); 939 if ( $serialized_block_name !== $block_name ) { 940 $has_block = str_contains( $post, '<!-- wp:' . $serialized_block_name . ' ' ); 941 } 942 } 943 944 return $has_block; 945 } 946 947 /** 948 * Returns an array of the names of all registered dynamic block types. 949 * 950 * @since 5.0.0 951 * 952 * @return string[] Array of dynamic block names. 953 */ 954 function get_dynamic_block_names() { 955 $dynamic_block_names = array(); 956 957 $block_types = WP_Block_Type_Registry::get_instance()->get_all_registered(); 958 foreach ( $block_types as $block_type ) { 959 if ( $block_type->is_dynamic() ) { 960 $dynamic_block_names[] = $block_type->name; 961 } 962 } 963 964 return $dynamic_block_names; 965 } 966 967 /** 968 * Retrieves block types hooked into the given block, grouped by anchor block type and the relative position. 969 * 970 * @since 6.4.0 971 * 972 * @return array[] Array of block types grouped by anchor block type and the relative position. 973 */ 974 function get_hooked_blocks() { 975 $block_types = WP_Block_Type_Registry::get_instance()->get_all_registered(); 976 $hooked_blocks = array(); 977 foreach ( $block_types as $block_type ) { 978 if ( ! ( $block_type instanceof WP_Block_Type ) || ! is_array( $block_type->block_hooks ) ) { 979 continue; 980 } 981 foreach ( $block_type->block_hooks as $anchor_block_type => $relative_position ) { 982 $hooked_blocks[ $anchor_block_type ][ $relative_position ][] = $block_type->name; 983 } 984 } 985 986 return $hooked_blocks; 987 } 988 989 /** 990 * Returns the markup for blocks hooked to the given anchor block in a specific relative position. 991 * 992 * @since 6.5.0 993 * @access private 994 * 995 * @param array $parsed_anchor_block The anchor block, in parsed block array format. 996 * @param string $relative_position The relative position of the hooked blocks. 997 * Can be one of 'before', 'after', 'first_child', or 'last_child'. 998 * @param array $hooked_blocks An array of hooked block types, grouped by anchor block and relative position. 999 * @param WP_Block_Template|WP_Post|array $context The block template, template part, or pattern that the anchor block belongs to. 1000 * @return string 1001 */ 1002 function insert_hooked_blocks( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) { 1003 $anchor_block_type = $parsed_anchor_block['blockName']; 1004 $hooked_block_types = isset( $anchor_block_type, $hooked_blocks[ $anchor_block_type ][ $relative_position ] ) 1005 ? $hooked_blocks[ $anchor_block_type ][ $relative_position ] 1006 : array(); 1007 1008 /** 1009 * Filters the list of hooked block types for a given anchor block type and relative position. 1010 * 1011 * @since 6.4.0 1012 * 1013 * @param string[] $hooked_block_types The list of hooked block types. 1014 * @param string $relative_position The relative position of the hooked blocks. 1015 * Can be one of 'before', 'after', 'first_child', or 'last_child'. 1016 * @param string $anchor_block_type The anchor block type. 1017 * @param WP_Block_Template|WP_Post|array $context The block template, template part, post object, 1018 * or pattern that the anchor block belongs to. 1019 */ 1020 $hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context ); 1021 1022 $markup = ''; 1023 foreach ( $hooked_block_types as $hooked_block_type ) { 1024 $parsed_hooked_block = array( 1025 'blockName' => $hooked_block_type, 1026 'attrs' => array(), 1027 'innerBlocks' => array(), 1028 'innerHTML' => '', 1029 'innerContent' => array(), 1030 ); 1031 1032 /** 1033 * Filters the parsed block array for a given hooked block. 1034 * 1035 * @since 6.5.0 1036 * 1037 * @param array|null $parsed_hooked_block The parsed block array for the given hooked block type, or null to suppress the block. 1038 * @param string $hooked_block_type The hooked block type name. 1039 * @param string $relative_position The relative position of the hooked block. 1040 * @param array $parsed_anchor_block The anchor block, in parsed block array format. 1041 * @param WP_Block_Template|WP_Post|array $context The block template, template part, post object, 1042 * or pattern that the anchor block belongs to. 1043 */ 1044 $parsed_hooked_block = apply_filters( 'hooked_block', $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context ); 1045 1046 /** 1047 * Filters the parsed block array for a given hooked block. 1048 * 1049 * The dynamic portion of the hook name, `$hooked_block_type`, refers to the block type name of the specific hooked block. 1050 * 1051 * @since 6.5.0 1052 * 1053 * @param array|null $parsed_hooked_block The parsed block array for the given hooked block type, or null to suppress the block. 1054 * @param string $hooked_block_type The hooked block type name. 1055 * @param string $relative_position The relative position of the hooked block. 1056 * @param array $parsed_anchor_block The anchor block, in parsed block array format. 1057 * @param WP_Block_Template|WP_Post|array $context The block template, template part, post object, 1058 * or pattern that the anchor block belongs to. 1059 */ 1060 $parsed_hooked_block = apply_filters( "hooked_block_{$hooked_block_type}", $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context ); 1061 1062 if ( null === $parsed_hooked_block ) { 1063 continue; 1064 } 1065 1066 // It's possible that the filter returned a block of a different type, so we explicitly 1067 // look for the original `$hooked_block_type` in the `ignoredHookedBlocks` metadata. 1068 if ( 1069 ! isset( $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] ) || 1070 ! in_array( $hooked_block_type, $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'], true ) 1071 ) { 1072 $markup .= serialize_block( $parsed_hooked_block ); 1073 } 1074 } 1075 1076 return $markup; 1077 } 1078 1079 /** 1080 * Adds a list of hooked block types to an anchor block's ignored hooked block types. 1081 * 1082 * This function is meant for internal use only. 1083 * 1084 * @since 6.5.0 1085 * @access private 1086 * 1087 * @param array $parsed_anchor_block The anchor block, in parsed block array format. 1088 * @param string $relative_position The relative position of the hooked blocks. 1089 * Can be one of 'before', 'after', 'first_child', or 'last_child'. 1090 * @param array $hooked_blocks An array of hooked block types, grouped by anchor block and relative position. 1091 * @param WP_Block_Template|WP_Post|array $context The block template, template part, or pattern that the anchor block belongs to. 1092 * @return string Empty string. 1093 */ 1094 function set_ignored_hooked_blocks_metadata( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) { 1095 $anchor_block_type = $parsed_anchor_block['blockName']; 1096 $hooked_block_types = isset( $anchor_block_type, $hooked_blocks[ $anchor_block_type ][ $relative_position ] ) 1097 ? $hooked_blocks[ $anchor_block_type ][ $relative_position ] 1098 : array(); 1099 1100 /** This filter is documented in wp-includes/blocks.php */ 1101 $hooked_block_types = apply_filters( 'hooked_block_types', $hooked_block_types, $relative_position, $anchor_block_type, $context ); 1102 if ( empty( $hooked_block_types ) ) { 1103 return ''; 1104 } 1105 1106 foreach ( $hooked_block_types as $index => $hooked_block_type ) { 1107 $parsed_hooked_block = array( 1108 'blockName' => $hooked_block_type, 1109 'attrs' => array(), 1110 'innerBlocks' => array(), 1111 'innerContent' => array(), 1112 ); 1113 1114 /** This filter is documented in wp-includes/blocks.php */ 1115 $parsed_hooked_block = apply_filters( 'hooked_block', $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context ); 1116 1117 /** This filter is documented in wp-includes/blocks.php */ 1118 $parsed_hooked_block = apply_filters( "hooked_block_{$hooked_block_type}", $parsed_hooked_block, $hooked_block_type, $relative_position, $parsed_anchor_block, $context ); 1119 1120 if ( null === $parsed_hooked_block ) { 1121 unset( $hooked_block_types[ $index ] ); 1122 } 1123 } 1124 1125 $previously_ignored_hooked_blocks = $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] ?? array(); 1126 1127 $parsed_anchor_block['attrs']['metadata']['ignoredHookedBlocks'] = array_unique( 1128 array_merge( 1129 $previously_ignored_hooked_blocks, 1130 $hooked_block_types 1131 ) 1132 ); 1133 1134 // Markup for the hooked blocks has already been created (in `insert_hooked_blocks`). 1135 return ''; 1136 } 1137 1138 /** 1139 * Runs the hooked blocks algorithm on the given content. 1140 * 1141 * @since 6.6.0 1142 * @since 6.7.0 Injects the `theme` attribute into Template Part blocks, even if no hooked blocks are registered. 1143 * @since 6.8.0 Have the `$context` parameter default to `null`, in which case `get_post()` will be called to use the current post as context. 1144 * @access private 1145 * 1146 * @param string $content Serialized content. 1147 * @param WP_Block_Template|WP_Post|array|null $context A block template, template part, post object, or pattern 1148 * that the blocks belong to. If set to `null`, `get_post()` 1149 * will be called to use the current post as context. 1150 * Default: `null`. 1151 * @param callable $callback A function that will be called for each block to generate 1152 * the markup for a given list of blocks that are hooked to it. 1153 * Default: 'insert_hooked_blocks'. 1154 * @return string The serialized markup. 1155 */ 1156 function apply_block_hooks_to_content( $content, $context = null, $callback = 'insert_hooked_blocks' ) { 1157 // Default to the current post if no context is provided. 1158 if ( null === $context ) { 1159 $context = get_post(); 1160 } 1161 1162 $hooked_blocks = get_hooked_blocks(); 1163 1164 $before_block_visitor = '_inject_theme_attribute_in_template_part_block'; 1165 $after_block_visitor = null; 1166 if ( ! empty( $hooked_blocks ) || has_filter( 'hooked_block_types' ) ) { 1167 $before_block_visitor = make_before_block_visitor( $hooked_blocks, $context, $callback ); 1168 $after_block_visitor = make_after_block_visitor( $hooked_blocks, $context, $callback ); 1169 } 1170 1171 $block_allows_multiple_instances = array(); 1172 /* 1173 * Remove hooked blocks from `$hooked_block_types` if they have `multiple` set to false and 1174 * are already present in `$content`. 1175 */ 1176 foreach ( $hooked_blocks as $anchor_block_type => $relative_positions ) { 1177 foreach ( $relative_positions as $relative_position => $hooked_block_types ) { 1178 foreach ( $hooked_block_types as $index => $hooked_block_type ) { 1179 $hooked_block_type_definition = 1180 WP_Block_Type_Registry::get_instance()->get_registered( $hooked_block_type ); 1181 1182 $block_allows_multiple_instances[ $hooked_block_type ] = 1183 block_has_support( $hooked_block_type_definition, 'multiple', true ); 1184 1185 if ( 1186 ! $block_allows_multiple_instances[ $hooked_block_type ] && 1187 has_block( $hooked_block_type, $content ) 1188 ) { 1189 unset( $hooked_blocks[ $anchor_block_type ][ $relative_position ][ $index ] ); 1190 } 1191 } 1192 if ( empty( $hooked_blocks[ $anchor_block_type ][ $relative_position ] ) ) { 1193 unset( $hooked_blocks[ $anchor_block_type ][ $relative_position ] ); 1194 } 1195 } 1196 if ( empty( $hooked_blocks[ $anchor_block_type ] ) ) { 1197 unset( $hooked_blocks[ $anchor_block_type ] ); 1198 } 1199 } 1200 1201 /* 1202 * We also need to cover the case where the hooked block is not present in 1203 * `$content` at first and we're allowed to insert it once -- but not again. 1204 */ 1205 $suppress_single_instance_blocks = static function ( $hooked_block_types ) use ( &$block_allows_multiple_instances, $content ) { 1206 static $single_instance_blocks_present_in_content = array(); 1207 foreach ( $hooked_block_types as $index => $hooked_block_type ) { 1208 if ( ! isset( $block_allows_multiple_instances[ $hooked_block_type ] ) ) { 1209 $hooked_block_type_definition = 1210 WP_Block_Type_Registry::get_instance()->get_registered( $hooked_block_type ); 1211 1212 $block_allows_multiple_instances[ $hooked_block_type ] = 1213 block_has_support( $hooked_block_type_definition, 'multiple', true ); 1214 } 1215 1216 if ( $block_allows_multiple_instances[ $hooked_block_type ] ) { 1217 continue; 1218 } 1219 1220 // The block doesn't allow multiple instances, so we need to check if it's already present. 1221 if ( 1222 in_array( $hooked_block_type, $single_instance_blocks_present_in_content, true ) || 1223 has_block( $hooked_block_type, $content ) 1224 ) { 1225 unset( $hooked_block_types[ $index ] ); 1226 } else { 1227 // We can insert the block once, but need to remember not to insert it again. 1228 $single_instance_blocks_present_in_content[] = $hooked_block_type; 1229 } 1230 } 1231 return $hooked_block_types; 1232 }; 1233 add_filter( 'hooked_block_types', $suppress_single_instance_blocks, PHP_INT_MAX ); 1234 $content = traverse_and_serialize_blocks( 1235 parse_blocks( $content ), 1236 $before_block_visitor, 1237 $after_block_visitor 1238 ); 1239 remove_filter( 'hooked_block_types', $suppress_single_instance_blocks, PHP_INT_MAX ); 1240 1241 return $content; 1242 } 1243 1244 /** 1245 * Run the Block Hooks algorithm on a post object's content. 1246 * 1247 * This function is different from `apply_block_hooks_to_content` in that 1248 * it takes ignored hooked block information from the post's metadata into 1249 * account. This ensures that any blocks hooked as first or last child 1250 * of the block that corresponds to the post type are handled correctly. 1251 * 1252 * @since 6.8.0 1253 * @since 7.0.0 Added the `$ignored_hooked_blocks_at_root` parameter. 1254 * @access private 1255 * 1256 * @param string $content Serialized content. 1257 * @param WP_Post|null $post A post object that the content belongs to. If set to `null`, 1258 * `get_post()` will be called to use the current post as context. 1259 * Default: `null`. 1260 * @param callable $callback A function that will be called for each block to generate 1261 * the markup for a given list of blocks that are hooked to it. 1262 * Default: 'insert_hooked_blocks'. 1263 * @param array|null $ignored_hooked_blocks_at_root A reference to an array that will be populated 1264 * with the ignored hooked blocks at the root level. 1265 * Default: `null`. 1266 * @return string The serialized markup. 1267 */ 1268 function apply_block_hooks_to_content_from_post_object( 1269 $content, 1270 $post = null, 1271 $callback = 'insert_hooked_blocks', 1272 &$ignored_hooked_blocks_at_root = null 1273 ) { 1274 // Default to the current post if no context is provided. 1275 if ( null === $post ) { 1276 $post = get_post(); 1277 } 1278 1279 if ( ! $post instanceof WP_Post ) { 1280 return apply_block_hooks_to_content( $content, $post, $callback ); 1281 } 1282 1283 /* 1284 * If the content was created using the classic editor or using a single Classic block 1285 * (`core/freeform`), it might not contain any block markup at all. 1286 * However, we still might need to inject hooked blocks in the first child or last child 1287 * positions of the parent block. To be able to apply the Block Hooks algorithm, we wrap 1288 * the content in a `core/freeform` wrapper block. 1289 */ 1290 if ( ! has_blocks( $content ) ) { 1291 $original_content = $content; 1292 1293 $content_wrapped_in_classic_block = get_comment_delimited_block_content( 1294 'core/freeform', 1295 array(), 1296 $content 1297 ); 1298 1299 $content = $content_wrapped_in_classic_block; 1300 } 1301 1302 $attributes = array(); 1303 1304 // If context is a post object, `ignoredHookedBlocks` information is stored in its post meta. 1305 $ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true ); 1306 if ( ! empty( $ignored_hooked_blocks ) ) { 1307 $ignored_hooked_blocks = json_decode( $ignored_hooked_blocks, true ); 1308 $attributes['metadata'] = array( 1309 'ignoredHookedBlocks' => $ignored_hooked_blocks, 1310 ); 1311 } 1312 1313 /* 1314 * We need to wrap the content in a temporary wrapper block with that metadata 1315 * so the Block Hooks algorithm can insert blocks that are hooked as first or last child 1316 * of the wrapper block. 1317 * To that end, we need to determine the wrapper block type based on the post type. 1318 */ 1319 if ( 'wp_navigation' === $post->post_type ) { 1320 $wrapper_block_type = 'core/navigation'; 1321 } elseif ( 'wp_block' === $post->post_type ) { 1322 $wrapper_block_type = 'core/block'; 1323 } else { 1324 $wrapper_block_type = 'core/post-content'; 1325 } 1326 1327 $content = get_comment_delimited_block_content( 1328 $wrapper_block_type, 1329 $attributes, 1330 $content 1331 ); 1332 1333 /* 1334 * We need to avoid inserting any blocks hooked into the `before` and `after` positions 1335 * of the temporary wrapper block that we create to wrap the content. 1336 * See https://core.trac.wordpress.org/ticket/63287 for more details. 1337 */ 1338 $suppress_blocks_from_insertion_before_and_after_wrapper_block = static function ( $hooked_block_types, $relative_position, $anchor_block_type ) use ( $wrapper_block_type ) { 1339 if ( 1340 $wrapper_block_type === $anchor_block_type && 1341 in_array( $relative_position, array( 'before', 'after' ), true ) 1342 ) { 1343 return array(); 1344 } 1345 return $hooked_block_types; 1346 }; 1347 1348 // Apply Block Hooks. 1349 add_filter( 'hooked_block_types', $suppress_blocks_from_insertion_before_and_after_wrapper_block, PHP_INT_MAX, 3 ); 1350 $content = apply_block_hooks_to_content( $content, $post, $callback ); 1351 remove_filter( 'hooked_block_types', $suppress_blocks_from_insertion_before_and_after_wrapper_block, PHP_INT_MAX ); 1352 1353 if ( null !== $ignored_hooked_blocks_at_root ) { 1354 // Check wrapper block's metadata for ignored hooked blocks at the root level, and populate the reference parameter if needed. 1355 $wrapper_block_markup = extract_serialized_parent_block( $content ); 1356 $wrapper_block = parse_blocks( $wrapper_block_markup )[0]; 1357 1358 if ( ! empty( $wrapper_block['attrs']['metadata']['ignoredHookedBlocks'] ) ) { 1359 $ignored_hooked_blocks_at_root = $wrapper_block['attrs']['metadata']['ignoredHookedBlocks']; 1360 } 1361 } 1362 1363 // Finally, we need to remove the temporary wrapper block. 1364 $content = remove_serialized_parent_block( $content ); 1365 1366 // If we wrapped the content in a `core/freeform` block, we also need to remove that. 1367 if ( ! empty( $content_wrapped_in_classic_block ) ) { 1368 /* 1369 * We cannot simply use remove_serialized_parent_block() here, 1370 * as that function assumes that the block wrapper is at the top level. 1371 * However, there might now be a hooked block inserted next to it 1372 * (as first or last child of the parent). 1373 */ 1374 $content = str_replace( $content_wrapped_in_classic_block, $original_content, $content ); 1375 } 1376 1377 return $content; 1378 } 1379 1380 /** 1381 * Accepts the serialized markup of a block and its inner blocks, and returns serialized markup of the inner blocks. 1382 * 1383 * @since 6.6.0 1384 * @access private 1385 * 1386 * @param string $serialized_block The serialized markup of a block and its inner blocks. 1387 * @return string The serialized markup of the inner blocks. 1388 */ 1389 function remove_serialized_parent_block( $serialized_block ) { 1390 $start = strpos( $serialized_block, '-->' ) + strlen( '-->' ); 1391 $end = strrpos( $serialized_block, '<!--' ); 1392 return substr( $serialized_block, $start, $end - $start ); 1393 } 1394 1395 /** 1396 * Accepts the serialized markup of a block and its inner blocks, and returns serialized markup of the wrapper block. 1397 * 1398 * @since 6.7.0 1399 * @access private 1400 * 1401 * @see remove_serialized_parent_block() 1402 * 1403 * @param string $serialized_block The serialized markup of a block and its inner blocks. 1404 * @return string The serialized markup of the wrapper block. 1405 */ 1406 function extract_serialized_parent_block( $serialized_block ) { 1407 $start = strpos( $serialized_block, '-->' ) + strlen( '-->' ); 1408 $end = strrpos( $serialized_block, '<!--' ); 1409 return substr( $serialized_block, 0, $start ) . substr( $serialized_block, $end ); 1410 } 1411 1412 /** 1413 * Updates the wp_postmeta with the list of ignored hooked blocks 1414 * where the inner blocks are stored as post content. 1415 * 1416 * @since 6.6.0 1417 * @since 6.8.0 Support non-`wp_navigation` post types. 1418 * @access private 1419 * 1420 * @param stdClass $post Post object. 1421 * @return stdClass The updated post object. 1422 */ 1423 function update_ignored_hooked_blocks_postmeta( $post ) { 1424 /* 1425 * In this scenario the user has likely tried to create a new post object via the REST API. 1426 * In which case we won't have a post ID to work with and store meta against. 1427 */ 1428 if ( empty( $post->ID ) ) { 1429 return $post; 1430 } 1431 1432 /* 1433 * Skip meta generation when consumers intentionally update specific fields 1434 * and omit the content update. 1435 */ 1436 if ( ! isset( $post->post_content ) ) { 1437 return $post; 1438 } 1439 1440 /* 1441 * Skip meta generation if post type is not set. 1442 */ 1443 if ( ! isset( $post->post_type ) ) { 1444 return $post; 1445 } 1446 1447 $attributes = array(); 1448 1449 $ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true ); 1450 if ( ! empty( $ignored_hooked_blocks ) ) { 1451 $ignored_hooked_blocks = json_decode( $ignored_hooked_blocks, true ); 1452 $attributes['metadata'] = array( 1453 'ignoredHookedBlocks' => $ignored_hooked_blocks, 1454 ); 1455 } 1456 1457 if ( 'wp_navigation' === $post->post_type ) { 1458 $wrapper_block_type = 'core/navigation'; 1459 } elseif ( 'wp_block' === $post->post_type ) { 1460 $wrapper_block_type = 'core/block'; 1461 } else { 1462 $wrapper_block_type = 'core/post-content'; 1463 } 1464 1465 $markup = get_comment_delimited_block_content( 1466 $wrapper_block_type, 1467 $attributes, 1468 $post->post_content 1469 ); 1470 1471 $existing_post = get_post( $post->ID ); 1472 // Merge the existing post object with the updated post object to pass to the block hooks algorithm for context. 1473 $context = (object) array_merge( (array) $existing_post, (array) $post ); 1474 $context = new WP_Post( $context ); // Convert to WP_Post object. 1475 $serialized_block = apply_block_hooks_to_content( $markup, $context, 'set_ignored_hooked_blocks_metadata' ); 1476 $root_block = parse_blocks( $serialized_block )[0]; 1477 1478 $ignored_hooked_blocks = $root_block['attrs']['metadata']['ignoredHookedBlocks'] ?? array(); 1479 1480 if ( ! empty( $ignored_hooked_blocks ) ) { 1481 $existing_ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true ); 1482 if ( ! empty( $existing_ignored_hooked_blocks ) ) { 1483 $existing_ignored_hooked_blocks = json_decode( $existing_ignored_hooked_blocks, true ); 1484 $ignored_hooked_blocks = array_unique( array_merge( $ignored_hooked_blocks, $existing_ignored_hooked_blocks ) ); 1485 } 1486 1487 $post->meta_input['_wp_ignored_hooked_blocks'] = json_encode( $ignored_hooked_blocks ); 1488 } 1489 1490 $post->post_content = remove_serialized_parent_block( $serialized_block ); 1491 return $post; 1492 } 1493 1494 /** 1495 * Returns the markup for blocks hooked to the given anchor block in a specific relative position and then 1496 * adds a list of hooked block types to an anchor block's ignored hooked block types. 1497 * 1498 * This function is meant for internal use only. 1499 * 1500 * @since 6.6.0 1501 * @access private 1502 * 1503 * @param array $parsed_anchor_block The anchor block, in parsed block array format. 1504 * @param string $relative_position The relative position of the hooked blocks. 1505 * Can be one of 'before', 'after', 'first_child', or 'last_child'. 1506 * @param array $hooked_blocks An array of hooked block types, grouped by anchor block and relative position. 1507 * @param WP_Block_Template|WP_Post|array $context The block template, template part, or pattern that the anchor block belongs to. 1508 * @return string 1509 */ 1510 function insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata( &$parsed_anchor_block, $relative_position, $hooked_blocks, $context ) { 1511 $markup = insert_hooked_blocks( $parsed_anchor_block, $relative_position, $hooked_blocks, $context ); 1512 $markup .= set_ignored_hooked_blocks_metadata( $parsed_anchor_block, $relative_position, $hooked_blocks, $context ); 1513 1514 return $markup; 1515 } 1516 1517 /** 1518 * Hooks into the REST API response for the Posts endpoint and adds the first and last inner blocks. 1519 * 1520 * @since 6.6.0 1521 * @since 6.8.0 Support non-`wp_navigation` post types. 1522 * @since 7.0.0 Set `_wp_ignored_hooked_blocks` meta in the response for blocks hooked at the root level. 1523 * 1524 * @param WP_REST_Response $response The response object. 1525 * @param WP_Post $post Post object. 1526 * @return WP_REST_Response The response object. 1527 */ 1528 function insert_hooked_blocks_into_rest_response( $response, $post ) { 1529 if ( empty( $response->data['content']['raw'] ) ) { 1530 return $response; 1531 } 1532 1533 $ignored_hooked_blocks_at_root = array(); 1534 $response->data['content']['raw'] = apply_block_hooks_to_content_from_post_object( 1535 $response->data['content']['raw'], 1536 $post, 1537 'insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata', 1538 $ignored_hooked_blocks_at_root 1539 ); 1540 1541 if ( ! empty( $ignored_hooked_blocks_at_root ) ) { 1542 $response->data['meta']['_wp_ignored_hooked_blocks'] = wp_json_encode( $ignored_hooked_blocks_at_root ); 1543 } 1544 1545 // If the rendered content was previously empty, we leave it like that. 1546 if ( empty( $response->data['content']['rendered'] ) ) { 1547 return $response; 1548 } 1549 1550 // `apply_block_hooks_to_content` is called above. Ensure it is not called again as a filter. 1551 $priority = has_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object' ); 1552 if ( false !== $priority ) { 1553 remove_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object', $priority ); 1554 } 1555 1556 /** This filter is documented in wp-includes/post-template.php */ 1557 $response->data['content']['rendered'] = apply_filters( 1558 'the_content', 1559 $response->data['content']['raw'] 1560 ); 1561 1562 // Restore the filter if it was set initially. 1563 if ( false !== $priority ) { 1564 add_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object', $priority ); 1565 } 1566 1567 return $response; 1568 } 1569 1570 /** 1571 * Returns a function that injects the theme attribute into, and hooked blocks before, a given block. 1572 * 1573 * The returned function can be used as `$pre_callback` argument to `traverse_and_serialize_block(s)`, 1574 * where it will inject the `theme` attribute into all Template Part blocks, and prepend the markup for 1575 * any blocks hooked `before` the given block and as its parent's `first_child`, respectively. 1576 * 1577 * This function is meant for internal use only. 1578 * 1579 * @since 6.4.0 1580 * @since 6.5.0 Added $callback argument. 1581 * @access private 1582 * 1583 * @param array $hooked_blocks An array of blocks hooked to another given block. 1584 * @param WP_Block_Template|WP_Post|array $context A block template, template part, post object, 1585 * or pattern that the blocks belong to. 1586 * @param callable $callback A function that will be called for each block to generate 1587 * the markup for a given list of blocks that are hooked to it. 1588 * Default: 'insert_hooked_blocks'. 1589 * @return callable A function that returns the serialized markup for the given block, 1590 * including the markup for any hooked blocks before it. 1591 */ 1592 function make_before_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) { 1593 /** 1594 * Injects hooked blocks before the given block, injects the `theme` attribute into Template Part blocks, and returns the serialized markup. 1595 * 1596 * If the current block is a Template Part block, inject the `theme` attribute. 1597 * Furthermore, prepend the markup for any blocks hooked `before` the given block and as its parent's 1598 * `first_child`, respectively, to the serialized markup for the given block. 1599 * 1600 * @param array $block The block to inject the theme attribute into, and hooked blocks before. Passed by reference. 1601 * @param array $parent_block The parent block of the given block. Passed by reference. Default null. 1602 * @param array $prev The previous sibling block of the given block. Default null. 1603 * @return string The serialized markup for the given block, with the markup for any hooked blocks prepended to it. 1604 */ 1605 return function ( &$block, &$parent_block = null, $prev = null ) use ( $hooked_blocks, $context, $callback ) { 1606 _inject_theme_attribute_in_template_part_block( $block ); 1607 1608 $markup = ''; 1609 1610 if ( $parent_block && ! $prev ) { 1611 // Candidate for first-child insertion. 1612 $markup .= call_user_func_array( 1613 $callback, 1614 array( &$parent_block, 'first_child', $hooked_blocks, $context ) 1615 ); 1616 } 1617 1618 $markup .= call_user_func_array( 1619 $callback, 1620 array( &$block, 'before', $hooked_blocks, $context ) 1621 ); 1622 1623 return $markup; 1624 }; 1625 } 1626 1627 /** 1628 * Returns a function that injects the hooked blocks after a given block. 1629 * 1630 * The returned function can be used as `$post_callback` argument to `traverse_and_serialize_block(s)`, 1631 * where it will append the markup for any blocks hooked `after` the given block and as its parent's 1632 * `last_child`, respectively. 1633 * 1634 * This function is meant for internal use only. 1635 * 1636 * @since 6.4.0 1637 * @since 6.5.0 Added $callback argument. 1638 * @access private 1639 * 1640 * @param array $hooked_blocks An array of blocks hooked to another block. 1641 * @param WP_Block_Template|WP_Post|array $context A block template, template part, post object, 1642 * or pattern that the blocks belong to. 1643 * @param callable $callback A function that will be called for each block to generate 1644 * the markup for a given list of blocks that are hooked to it. 1645 * Default: 'insert_hooked_blocks'. 1646 * @return callable A function that returns the serialized markup for the given block, 1647 * including the markup for any hooked blocks after it. 1648 */ 1649 function make_after_block_visitor( $hooked_blocks, $context, $callback = 'insert_hooked_blocks' ) { 1650 /** 1651 * Injects hooked blocks after the given block, and returns the serialized markup. 1652 * 1653 * Append the markup for any blocks hooked `after` the given block and as its parent's 1654 * `last_child`, respectively, to the serialized markup for the given block. 1655 * 1656 * @param array $block The block to inject the hooked blocks after. Passed by reference. 1657 * @param array $parent_block The parent block of the given block. Passed by reference. Default null. 1658 * @param array $next The next sibling block of the given block. Default null. 1659 * @return string The serialized markup for the given block, with the markup for any hooked blocks appended to it. 1660 */ 1661 return function ( &$block, &$parent_block = null, $next = null ) use ( $hooked_blocks, $context, $callback ) { 1662 $markup = call_user_func_array( 1663 $callback, 1664 array( &$block, 'after', $hooked_blocks, $context ) 1665 ); 1666 1667 if ( $parent_block && ! $next ) { 1668 // Candidate for last-child insertion. 1669 $markup .= call_user_func_array( 1670 $callback, 1671 array( &$parent_block, 'last_child', $hooked_blocks, $context ) 1672 ); 1673 } 1674 1675 return $markup; 1676 }; 1677 } 1678 1679 /** 1680 * Given an array of attributes, returns a string in the serialized attributes 1681 * format prepared for post content. 1682 * 1683 * The serialized result is a JSON-encoded string, with unicode escape sequence 1684 * substitution for characters which might otherwise interfere with embedding 1685 * the result in an HTML comment. 1686 * 1687 * This function must produce output that remains in sync with the output of 1688 * the serializeAttributes JavaScript function in the block editor in order 1689 * to ensure consistent operation between PHP and JavaScript. 1690 * 1691 * @since 5.3.1 1692 * 1693 * @param array $block_attributes Attributes object. 1694 * @return string Serialized attributes. 1695 */ 1696 function serialize_block_attributes( $block_attributes ) { 1697 $encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); 1698 1699 return strtr( 1700 $encoded_attributes, 1701 array( 1702 '\\\\' => '\\u005c', 1703 '--' => '\\u002d\\u002d', 1704 '<' => '\\u003c', 1705 '>' => '\\u003e', 1706 '&' => '\\u0026', 1707 '\\"' => '\\u0022', 1708 ) 1709 ); 1710 } 1711 1712 /** 1713 * Returns the block name to use for serialization. This will remove the default 1714 * "core/" namespace from a block name. 1715 * 1716 * @since 5.3.1 1717 * 1718 * @param string|null $block_name Optional. Original block name. Null if the block name is unknown, 1719 * e.g. Classic blocks have their name set to null. Default null. 1720 * @return string Block name to use for serialization. 1721 */ 1722 function strip_core_block_namespace( $block_name = null ) { 1723 if ( is_string( $block_name ) && str_starts_with( $block_name, 'core/' ) ) { 1724 return substr( $block_name, 5 ); 1725 } 1726 1727 return $block_name; 1728 } 1729 1730 /** 1731 * Returns the content of a block, including comment delimiters. 1732 * 1733 * @since 5.3.1 1734 * 1735 * @param string|null $block_name Block name. Null if the block name is unknown, 1736 * e.g. Classic blocks have their name set to null. 1737 * @param array $block_attributes Block attributes. 1738 * @param string $block_content Block save content. 1739 * @return string Comment-delimited block content. 1740 */ 1741 function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) { 1742 if ( is_null( $block_name ) ) { 1743 return $block_content; 1744 } 1745 1746 $serialized_block_name = strip_core_block_namespace( $block_name ); 1747 $serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' '; 1748 1749 if ( empty( $block_content ) ) { 1750 return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes ); 1751 } 1752 1753 return sprintf( 1754 '<!-- wp:%s %s-->%s<!-- /wp:%s -->', 1755 $serialized_block_name, 1756 $serialized_attributes, 1757 $block_content, 1758 $serialized_block_name 1759 ); 1760 } 1761 1762 /** 1763 * Returns the content of a block, including comment delimiters, serializing all 1764 * attributes from the given parsed block. 1765 * 1766 * This should be used when preparing a block to be saved to post content. 1767 * Prefer `render_block` when preparing a block for display. Unlike 1768 * `render_block`, this does not evaluate a block's `render_callback`, and will 1769 * instead preserve the markup as parsed. 1770 * 1771 * @since 5.3.1 1772 * 1773 * @param array $block { 1774 * An associative array of a single parsed block object. See WP_Block_Parser_Block. 1775 * 1776 * @type string|null $blockName Name of block. 1777 * @type array $attrs Attributes from block comment delimiters. 1778 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 1779 * have the same structure as this one. 1780 * @type string $innerHTML HTML from inside block comment delimiters. 1781 * @type array $innerContent List of string fragments and null markers where 1782 * inner blocks were found. 1783 * } 1784 * @return string String of rendered HTML. 1785 */ 1786 function serialize_block( $block ) { 1787 $block_content = ''; 1788 1789 $index = 0; 1790 foreach ( $block['innerContent'] as $chunk ) { 1791 $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] ); 1792 } 1793 1794 if ( ! is_array( $block['attrs'] ) ) { 1795 $block['attrs'] = array(); 1796 } 1797 1798 return get_comment_delimited_block_content( 1799 $block['blockName'], 1800 $block['attrs'], 1801 $block_content 1802 ); 1803 } 1804 1805 /** 1806 * Returns a joined string of the aggregate serialization of the given 1807 * parsed blocks. 1808 * 1809 * @since 5.3.1 1810 * 1811 * @param array[] $blocks { 1812 * Array of block structures. 1813 * 1814 * @type array ...$0 { 1815 * An associative array of a single parsed block object. See WP_Block_Parser_Block. 1816 * 1817 * @type string|null $blockName Name of block. 1818 * @type array $attrs Attributes from block comment delimiters. 1819 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 1820 * have the same structure as this one. 1821 * @type string $innerHTML HTML from inside block comment delimiters. 1822 * @type array $innerContent List of string fragments and null markers where 1823 * inner blocks were found. 1824 * } 1825 * } 1826 * @return string String of rendered HTML. 1827 */ 1828 function serialize_blocks( $blocks ) { 1829 return implode( '', array_map( 'serialize_block', $blocks ) ); 1830 } 1831 1832 /** 1833 * Traverses a parsed block tree and applies callbacks before and after serializing it. 1834 * 1835 * Recursively traverses the block and its inner blocks and applies the two callbacks provided as 1836 * arguments, the first one before serializing the block, and the second one after serializing it. 1837 * If either callback returns a string value, it will be prepended and appended to the serialized 1838 * block markup, respectively. 1839 * 1840 * The callbacks will receive a reference to the current block as their first argument, so that they 1841 * can also modify it, and the current block's parent block as second argument. Finally, the 1842 * `$pre_callback` receives the previous block, whereas the `$post_callback` receives 1843 * the next block as third argument. 1844 * 1845 * Serialized blocks are returned including comment delimiters, and with all attributes serialized. 1846 * 1847 * This function should be used when there is a need to modify the saved block, or to inject markup 1848 * into the return value. Prefer `serialize_block` when preparing a block to be saved to post content. 1849 * 1850 * This function is meant for internal use only. 1851 * 1852 * @since 6.4.0 1853 * @access private 1854 * 1855 * @see serialize_block() 1856 * 1857 * @param array $block An associative array of a single parsed block object. See WP_Block_Parser_Block. 1858 * @param callable $pre_callback Callback to run on each block in the tree before it is traversed and serialized. 1859 * It is called with the following arguments: &$block, $parent_block, $previous_block. 1860 * Its string return value will be prepended to the serialized block markup. 1861 * @param callable $post_callback Callback to run on each block in the tree after it is traversed and serialized. 1862 * It is called with the following arguments: &$block, $parent_block, $next_block. 1863 * Its string return value will be appended to the serialized block markup. 1864 * @return string Serialized block markup. 1865 */ 1866 function traverse_and_serialize_block( $block, $pre_callback = null, $post_callback = null ) { 1867 $block_content = ''; 1868 $block_index = 0; 1869 1870 foreach ( $block['innerContent'] as $chunk ) { 1871 if ( is_string( $chunk ) ) { 1872 $block_content .= $chunk; 1873 } else { 1874 $inner_block = $block['innerBlocks'][ $block_index ]; 1875 1876 if ( is_callable( $pre_callback ) ) { 1877 $prev = 0 === $block_index 1878 ? null 1879 : $block['innerBlocks'][ $block_index - 1 ]; 1880 1881 $block_content .= call_user_func_array( 1882 $pre_callback, 1883 array( &$inner_block, &$block, $prev ) 1884 ); 1885 } 1886 1887 if ( is_callable( $post_callback ) ) { 1888 $next = count( $block['innerBlocks'] ) - 1 === $block_index 1889 ? null 1890 : $block['innerBlocks'][ $block_index + 1 ]; 1891 1892 $post_markup = call_user_func_array( 1893 $post_callback, 1894 array( &$inner_block, &$block, $next ) 1895 ); 1896 } 1897 1898 $block_content .= traverse_and_serialize_block( $inner_block, $pre_callback, $post_callback ); 1899 $block_content .= $post_markup ?? ''; 1900 1901 ++$block_index; 1902 } 1903 } 1904 1905 if ( ! is_array( $block['attrs'] ) ) { 1906 $block['attrs'] = array(); 1907 } 1908 1909 return get_comment_delimited_block_content( 1910 $block['blockName'], 1911 $block['attrs'], 1912 $block_content 1913 ); 1914 } 1915 1916 /** 1917 * Replaces patterns in a block tree with their content. 1918 * 1919 * @since 6.6.0 1920 * @since 7.0.0 Adds metadata to attributes of single-pattern container blocks. 1921 * 1922 * @param array[] $blocks { 1923 * An array of blocks. 1924 * 1925 * @type array ...$0 { 1926 * An associative array of a single parsed block object. See {@see WP_Block_Parser_Block}. 1927 * 1928 * @type string|null $blockName Required. Name of block. 1929 * @type array $attrs Required. Attributes from block comment delimiters. 1930 * @type array[] $innerBlocks Required. List of inner blocks. An array of arrays that 1931 * have the same structure as this one. 1932 * @type string $innerHTML Required. HTML from inside block comment delimiters. 1933 * @type array $innerContent Required. List of string fragments and null markers where 1934 * inner blocks were found. 1935 * } 1936 * } 1937 * @return array[] { 1938 * An array of blocks with patterns replaced by their content. 1939 * 1940 * @type array ...$0 { 1941 * An associative array of a single parsed block object. See {@see WP_Block_Parser_Block}. 1942 * 1943 * @type string|null $blockName Name of block. 1944 * @type array $attrs Attributes from block comment delimiters. 1945 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 1946 * have the same structure as this one. 1947 * @type string $innerHTML HTML from inside block comment delimiters. 1948 * @type array $innerContent List of string fragments and null markers where 1949 * inner blocks were found. 1950 * @type mixed ...$key Any other keys a block passed in carries, which 1951 * are kept, except where a `core/pattern` block is 1952 * replaced by its pattern's blocks, or removed as 1953 * recursive. 1954 * } 1955 * } 1956 */ 1957 function resolve_pattern_blocks( $blocks ) { 1958 static $inner_content; 1959 // Keep track of seen references to avoid infinite loops. 1960 static $seen_refs = array(); 1961 $i = 0; 1962 while ( $i < count( $blocks ) ) { 1963 if ( 'core/pattern' === $blocks[ $i ]['blockName'] ) { 1964 $attrs = $blocks[ $i ]['attrs']; 1965 1966 if ( empty( $attrs['slug'] ) ) { 1967 ++$i; 1968 continue; 1969 } 1970 1971 $slug = $attrs['slug']; 1972 1973 if ( isset( $seen_refs[ $slug ] ) ) { 1974 // Skip recursive patterns. 1975 array_splice( $blocks, $i, 1 ); 1976 continue; 1977 } 1978 1979 $registry = WP_Block_Patterns_Registry::get_instance(); 1980 $pattern = $registry->get_registered( $slug ); 1981 1982 // Skip unknown patterns. 1983 if ( ! $pattern ) { 1984 ++$i; 1985 continue; 1986 } 1987 1988 $blocks_to_insert = parse_blocks( trim( $pattern['content'] ) ); 1989 1990 /* 1991 * For single-root patterns, add the pattern name to make this a pattern instance in the editor. 1992 * If the pattern has metadata, merge it with the existing metadata. 1993 */ 1994 if ( count( $blocks_to_insert ) === 1 ) { 1995 $block_metadata = $blocks_to_insert[0]['attrs']['metadata'] ?? array(); 1996 $block_metadata['patternName'] = $slug; 1997 1998 /* 1999 * Merge pattern metadata with existing block metadata. 2000 * Pattern metadata takes precedence, but existing block metadata 2001 * is preserved as a fallback when the pattern doesn't define that field. 2002 * Only the defined fields (name, description, categories) are updated; 2003 * other metadata keys are preserved. 2004 */ 2005 foreach ( array( 2006 'name' => 'title', // 'title' is the field in the pattern object 'name' is the field in the block metadata. 2007 'description' => 'description', 2008 'categories' => 'categories', 2009 ) as $key => $pattern_key ) { 2010 $value = $pattern[ $pattern_key ] ?? $block_metadata[ $key ] ?? null; 2011 if ( $value ) { 2012 $block_metadata[ $key ] = is_array( $value ) 2013 ? array_map( 'sanitize_text_field', $value ) 2014 : sanitize_text_field( $value ); 2015 } 2016 } 2017 2018 $blocks_to_insert[0]['attrs']['metadata'] = $block_metadata; 2019 } 2020 2021 $seen_refs[ $slug ] = true; 2022 $prev_inner_content = $inner_content; 2023 $inner_content = null; 2024 $blocks_to_insert = resolve_pattern_blocks( $blocks_to_insert ); 2025 $inner_content = $prev_inner_content; 2026 unset( $seen_refs[ $slug ] ); 2027 array_splice( $blocks, $i, 1, $blocks_to_insert ); 2028 2029 // If we have inner content, we need to insert nulls in the 2030 // inner content array, otherwise serialize_blocks will skip 2031 // blocks. 2032 if ( $inner_content ) { 2033 $null_indices = array_keys( $inner_content, null, true ); 2034 $content_index = $null_indices[ $i ]; 2035 $nulls = array_fill( 0, count( $blocks_to_insert ), null ); 2036 array_splice( $inner_content, $content_index, 1, $nulls ); 2037 } 2038 2039 // Skip inserted blocks. 2040 $i += count( $blocks_to_insert ); 2041 } else { 2042 if ( ! empty( $blocks[ $i ]['innerBlocks'] ) ) { 2043 $prev_inner_content = $inner_content; 2044 $inner_content = $blocks[ $i ]['innerContent']; 2045 $blocks[ $i ]['innerBlocks'] = resolve_pattern_blocks( 2046 $blocks[ $i ]['innerBlocks'] 2047 ); 2048 $blocks[ $i ]['innerContent'] = $inner_content; 2049 $inner_content = $prev_inner_content; 2050 } 2051 ++$i; 2052 } 2053 } 2054 return $blocks; 2055 } 2056 2057 /** 2058 * Given an array of parsed block trees, applies callbacks before and after serializing them and 2059 * returns their concatenated output. 2060 * 2061 * Recursively traverses the blocks and their inner blocks and applies the two callbacks provided as 2062 * arguments, the first one before serializing a block, and the second one after serializing. 2063 * If either callback returns a string value, it will be prepended and appended to the serialized 2064 * block markup, respectively. 2065 * 2066 * The callbacks will receive a reference to the current block as their first argument, so that they 2067 * can also modify it, and the current block's parent block as second argument. Finally, the 2068 * `$pre_callback` receives the previous block, whereas the `$post_callback` receives 2069 * the next block as third argument. 2070 * 2071 * Serialized blocks are returned including comment delimiters, and with all attributes serialized. 2072 * 2073 * This function should be used when there is a need to modify the saved blocks, or to inject markup 2074 * into the return value. Prefer `serialize_blocks` when preparing blocks to be saved to post content. 2075 * 2076 * This function is meant for internal use only. 2077 * 2078 * @since 6.4.0 2079 * @access private 2080 * 2081 * @see serialize_blocks() 2082 * 2083 * @param array[] $blocks An array of parsed blocks. See WP_Block_Parser_Block. 2084 * @param callable $pre_callback Callback to run on each block in the tree before it is traversed and serialized. 2085 * It is called with the following arguments: &$block, $parent_block, $previous_block. 2086 * Its string return value will be prepended to the serialized block markup. 2087 * @param callable $post_callback Callback to run on each block in the tree after it is traversed and serialized. 2088 * It is called with the following arguments: &$block, $parent_block, $next_block. 2089 * Its string return value will be appended to the serialized block markup. 2090 * @return string Serialized block markup. 2091 */ 2092 function traverse_and_serialize_blocks( $blocks, $pre_callback = null, $post_callback = null ) { 2093 $result = ''; 2094 $parent_block = null; // At the top level, there is no parent block to pass to the callbacks; yet the callbacks expect a reference. 2095 2096 $pre_callback_is_callable = is_callable( $pre_callback ); 2097 $post_callback_is_callable = is_callable( $post_callback ); 2098 2099 foreach ( $blocks as $index => $block ) { 2100 if ( $pre_callback_is_callable ) { 2101 $prev = 0 === $index 2102 ? null 2103 : $blocks[ $index - 1 ]; 2104 2105 $result .= call_user_func_array( 2106 $pre_callback, 2107 array( &$block, &$parent_block, $prev ) 2108 ); 2109 } 2110 2111 if ( $post_callback_is_callable ) { 2112 $next = count( $blocks ) - 1 === $index 2113 ? null 2114 : $blocks[ $index + 1 ]; 2115 2116 $post_markup = call_user_func_array( 2117 $post_callback, 2118 array( &$block, &$parent_block, $next ) 2119 ); 2120 } 2121 2122 $result .= traverse_and_serialize_block( $block, $pre_callback, $post_callback ); 2123 $result .= $post_markup ?? ''; 2124 } 2125 2126 return $result; 2127 } 2128 2129 /** 2130 * Filters and sanitizes block content to remove non-allowable HTML 2131 * from parsed block attribute values. 2132 * 2133 * @since 5.3.1 2134 * 2135 * @param string $text Text that may contain block content. 2136 * @param array[]|string $allowed_html Optional. An array of allowed HTML elements and attributes, 2137 * or a context name such as 'post'. See wp_kses_allowed_html() 2138 * for the list of accepted context names. Default 'post'. 2139 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 2140 * Defaults to the result of wp_allowed_protocols(). 2141 * @return string The filtered and sanitized content result. 2142 */ 2143 function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) { 2144 $result = ''; 2145 2146 if ( str_contains( $text, '<!--' ) && str_contains( $text, '--->' ) ) { 2147 $text = preg_replace_callback( '%<!--(.*?)--->%', '_filter_block_content_callback', $text ); 2148 } 2149 2150 $blocks = parse_blocks( $text ); 2151 foreach ( $blocks as $block ) { 2152 $block = filter_block_kses( $block, $allowed_html, $allowed_protocols ); 2153 $result .= serialize_block( $block ); 2154 } 2155 2156 return $result; 2157 } 2158 2159 /** 2160 * Callback used for regular expression replacement in filter_block_content(). 2161 * 2162 * @since 6.2.1 2163 * @access private 2164 * 2165 * @param array $matches Array of preg_replace_callback matches. 2166 * @return string Replacement string. 2167 */ 2168 function _filter_block_content_callback( $matches ) { 2169 return '<!--' . rtrim( $matches[1], '-' ) . '-->'; 2170 } 2171 2172 /** 2173 * Filters and sanitizes a parsed block to remove non-allowable HTML 2174 * from block attribute values. 2175 * 2176 * @since 5.3.1 2177 * 2178 * @param WP_Block_Parser_Block $block The parsed block object. 2179 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2180 * or a context name such as 'post'. See wp_kses_allowed_html() 2181 * for the list of accepted context names. 2182 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 2183 * Defaults to the result of wp_allowed_protocols(). 2184 * @return array The filtered and sanitized block object result. 2185 */ 2186 function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) { 2187 $block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols, $block ); 2188 2189 if ( is_array( $block['innerBlocks'] ) ) { 2190 foreach ( $block['innerBlocks'] as $i => $inner_block ) { 2191 $block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols ); 2192 } 2193 } 2194 2195 return $block; 2196 } 2197 2198 /** 2199 * Filters and sanitizes a parsed block attribute value to remove 2200 * non-allowable HTML. 2201 * 2202 * @since 5.3.1 2203 * @since 6.5.5 Added the `$block_context` parameter. 2204 * 2205 * @param string[]|string $value The attribute value to filter. 2206 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2207 * or a context name such as 'post'. See wp_kses_allowed_html() 2208 * for the list of accepted context names. 2209 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 2210 * Defaults to the result of wp_allowed_protocols(). 2211 * @param array $block_context Optional. The block the attribute belongs to, in parsed block array format. 2212 * @return string[]|string The filtered and sanitized result. 2213 */ 2214 function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array(), $block_context = null ) { 2215 if ( is_array( $value ) ) { 2216 foreach ( $value as $key => $inner_value ) { 2217 $filtered_key = filter_block_kses_value( $key, $allowed_html, $allowed_protocols, $block_context ); 2218 $filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols, $block_context ); 2219 2220 if ( isset( $block_context['blockName'] ) && 'core/template-part' === $block_context['blockName'] ) { 2221 $filtered_value = filter_block_core_template_part_attributes( $filtered_value, $filtered_key, $allowed_html ); 2222 } 2223 if ( $filtered_key !== $key ) { 2224 unset( $value[ $key ] ); 2225 } 2226 2227 $value[ $filtered_key ] = $filtered_value; 2228 } 2229 } elseif ( is_string( $value ) ) { 2230 return wp_kses( $value, $allowed_html, $allowed_protocols ); 2231 } 2232 2233 return $value; 2234 } 2235 2236 /** 2237 * Sanitizes the value of the Template Part block's `tagName` attribute. 2238 * 2239 * @since 6.5.5 2240 * 2241 * @param string $attribute_value The attribute value to filter. 2242 * @param string $attribute_name The attribute name. 2243 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2244 * or a context name such as 'post'. See wp_kses_allowed_html() 2245 * for the list of accepted context names. 2246 * @return string The sanitized attribute value. 2247 */ 2248 function filter_block_core_template_part_attributes( $attribute_value, $attribute_name, $allowed_html ) { 2249 if ( empty( $attribute_value ) || 'tagName' !== $attribute_name ) { 2250 return $attribute_value; 2251 } 2252 if ( ! is_array( $allowed_html ) ) { 2253 $allowed_html = wp_kses_allowed_html( $allowed_html ); 2254 } 2255 return isset( $allowed_html[ $attribute_value ] ) ? $attribute_value : ''; 2256 } 2257 2258 /** 2259 * Parses blocks out of a content string, and renders those appropriate for the excerpt. 2260 * 2261 * As the excerpt should be a small string of text relevant to the full post content, 2262 * this function renders the blocks that are most likely to contain such text. 2263 * 2264 * @since 5.0.0 2265 * 2266 * @param string $content The content to parse. 2267 * @return string The parsed and filtered content. 2268 */ 2269 function excerpt_remove_blocks( $content ) { 2270 if ( ! has_blocks( $content ) ) { 2271 return $content; 2272 } 2273 2274 $allowed_inner_blocks = array( 2275 // Classic blocks have their blockName set to null. 2276 null, 2277 'core/freeform', 2278 'core/heading', 2279 'core/html', 2280 'core/list', 2281 'core/list-item', 2282 'core/media-text', 2283 'core/paragraph', 2284 'core/preformatted', 2285 'core/pullquote', 2286 'core/quote', 2287 'core/table', 2288 'core/verse', 2289 ); 2290 2291 $allowed_wrapper_blocks = array( 2292 'core/columns', 2293 'core/column', 2294 'core/group', 2295 'core/list', 2296 ); 2297 2298 /** 2299 * Filters the list of blocks that can be used as wrapper blocks, allowing 2300 * excerpts to be generated from the `innerBlocks` of these wrappers. 2301 * 2302 * @since 5.8.0 2303 * 2304 * @param string[] $allowed_wrapper_blocks The list of names of allowed wrapper blocks. 2305 */ 2306 $allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks ); 2307 2308 $allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks ); 2309 2310 /** 2311 * Filters the list of blocks that can contribute to the excerpt. 2312 * 2313 * If a dynamic block is added to this list, it must not generate another 2314 * excerpt, as this will cause an infinite loop to occur. 2315 * 2316 * @since 5.0.0 2317 * 2318 * @param string[] $allowed_blocks The list of names of allowed blocks. 2319 */ 2320 $allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks ); 2321 $blocks = parse_blocks( $content ); 2322 $output = ''; 2323 2324 foreach ( $blocks as $block ) { 2325 // Hide the block whenever the value is boolean false, regardless of the 2326 // block's current visibility support. This prevents blocks that previously 2327 // supported visibility from unintentionally appearing on the front end 2328 // after their support was disabled. 2329 if ( false === ( $block['attrs']['metadata']['blockVisibility'] ?? null ) ) { 2330 continue; 2331 } 2332 2333 if ( in_array( $block['blockName'], $allowed_blocks, true ) ) { 2334 if ( ! empty( $block['innerBlocks'] ) ) { 2335 if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) { 2336 $output .= _excerpt_render_inner_blocks( $block, $allowed_blocks ); 2337 continue; 2338 } 2339 2340 // Skip the block if it has disallowed or nested inner blocks. 2341 foreach ( $block['innerBlocks'] as $inner_block ) { 2342 if ( 2343 ! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) || 2344 ! empty( $inner_block['innerBlocks'] ) 2345 ) { 2346 continue 2; 2347 } 2348 } 2349 } 2350 2351 $output .= render_block( $block ); 2352 } 2353 } 2354 2355 return $output; 2356 } 2357 2358 /** 2359 * Removes recognized footnote reference markup from a given string. 2360 * 2361 * Example: 2362 * 2363 * $content = 'Never<sup data-fn="abc-123" class="fn"><a href="#abc-123" id="abc-123">1</a></sup> say never.'; 2364 * 'Never say never' === excerpt_remove_footnotes( $content ); 2365 * 2366 * @since 6.3.0 2367 * 2368 * @param string $content HTML which might contain footnote references from the block editor. 2369 * @return string Given input HTML without the footnote references. 2370 */ 2371 function excerpt_remove_footnotes( $content ) { 2372 if ( ! str_contains( $content, 'data-fn' ) ) { 2373 return $content; 2374 } 2375 2376 $processor = new class( $content ) extends WP_HTML_Tag_Processor { 2377 public function is_whitespace_text_node(): bool { 2378 if ( self::STATE_TEXT_NODE !== $this->parser_state ) { 2379 return false; 2380 } 2381 2382 $this->subdivide_text_appropriately(); 2383 return self::TEXT_IS_WHITESPACE === $this->text_node_classification; 2384 } 2385 2386 public function get_span(): WP_HTML_Span { 2387 $this->set_bookmark( 'here' ); 2388 2389 return $this->bookmarks['here']; 2390 } 2391 }; 2392 2393 $output = ''; 2394 $at = 0; 2395 $reprocess_token = false; 2396 2397 while ( $reprocess_token || $processor->next_token() ) { 2398 $reprocess_token = false; 2399 2400 // Match the <sup data-fn="..." class="..."> opening tag. 2401 if ( 2402 $processor->is_tag_closer() || 2403 'SUP' !== $processor->get_tag() || 2404 null === $processor->get_attribute( 'data-fn' ) || 2405 null === $processor->get_attribute( 'class' ) 2406 ) { 2407 continue; 2408 } 2409 2410 $footnote_opening = $processor->get_span(); 2411 2412 if ( ! $processor->next_token() ) { 2413 break; 2414 } 2415 2416 // Skip any whitespace-only text between the tags. 2417 if ( '#text' === $processor->get_token_name() ) { 2418 if ( ! $processor->is_whitespace_text_node() ) { 2419 $reprocess_token = true; 2420 continue; 2421 } 2422 2423 $processor->next_token(); 2424 } 2425 2426 // Match the <a href="..." id="..."> opening tag. 2427 if ( 2428 $processor->is_tag_closer() || 2429 'A' !== $processor->get_token_name() || 2430 null === $processor->get_attribute( 'href' ) || 2431 null === $processor->get_attribute( 'id' ) 2432 ) { 2433 $reprocess_token = true; 2434 continue; 2435 } 2436 2437 // Match an all-digit text node. 2438 if ( ! $processor->next_token() || '#text' !== $processor->get_token_name() ) { 2439 $reprocess_token = true; 2440 continue; 2441 } 2442 2443 $footnote_number = $processor->get_modifiable_text(); 2444 $digit_count = strspn( $footnote_number, '0123456789' ); 2445 if ( 0 === $digit_count || strlen( $footnote_number ) !== $digit_count ) { 2446 $reprocess_token = true; 2447 continue; 2448 } 2449 2450 // Match the closing </a> tag. 2451 if ( 2452 ! $processor->next_token() || 2453 'A' !== $processor->get_token_name() || 2454 ! $processor->is_tag_closer() 2455 ) { 2456 $reprocess_token = true; 2457 continue; 2458 } 2459 2460 if ( ! $processor->next_token() ) { 2461 break; 2462 } 2463 2464 // Skip any whitespace-only text between the tags. 2465 if ( '#text' === $processor->get_token_name() ) { 2466 if ( ! $processor->is_whitespace_text_node() ) { 2467 $reprocess_token = true; 2468 continue; 2469 } 2470 2471 $processor->next_token(); 2472 } 2473 2474 // Match the closing </sup> tag. 2475 if ( 2476 'SUP' !== $processor->get_token_name() || 2477 ! $processor->is_tag_closer() 2478 ) { 2479 $reprocess_token = true; 2480 continue; 2481 } 2482 2483 $footnote_closing = $processor->get_span(); 2484 2485 // Remove the section and continue. 2486 $output .= substr( $content, $at, $footnote_opening->start - $at ); 2487 $at = $footnote_closing->start + $footnote_closing->length; 2488 } 2489 2490 // No footnotes were found and removed: return the original input. 2491 if ( 0 === $at ) { 2492 return $content; 2493 } 2494 2495 if ( $at < strlen( $content ) ) { 2496 $output .= substr( $content, $at ); 2497 } 2498 2499 return $output; 2500 } 2501 2502 /** 2503 * Renders inner blocks from the allowed wrapper blocks 2504 * for generating an excerpt. 2505 * 2506 * @since 5.8.0 2507 * @access private 2508 * 2509 * @param array $parsed_block The parsed block. 2510 * @param array $allowed_blocks The list of allowed inner blocks. 2511 * @return string The rendered inner blocks. 2512 */ 2513 function _excerpt_render_inner_blocks( $parsed_block, $allowed_blocks ) { 2514 $output = ''; 2515 2516 foreach ( $parsed_block['innerBlocks'] as $inner_block ) { 2517 // Hide the block whenever the value is boolean false, regardless of the 2518 // block's current visibility support. This prevents blocks that previously 2519 // supported visibility from unintentionally appearing on the front end 2520 // after their support was disabled. 2521 if ( false === ( $inner_block['attrs']['metadata']['blockVisibility'] ?? null ) ) { 2522 continue; 2523 } 2524 2525 if ( ! in_array( $inner_block['blockName'], $allowed_blocks, true ) ) { 2526 continue; 2527 } 2528 2529 if ( empty( $inner_block['innerBlocks'] ) ) { 2530 $output .= render_block( $inner_block ); 2531 } else { 2532 $output .= _excerpt_render_inner_blocks( $inner_block, $allowed_blocks ); 2533 } 2534 } 2535 2536 return $output; 2537 } 2538 2539 /** 2540 * Renders a single block into a HTML string. 2541 * 2542 * @since 5.0.0 2543 * 2544 * @global WP_Post $post The post to edit. 2545 * 2546 * @param array $parsed_block { 2547 * An associative array of the block being rendered. See WP_Block_Parser_Block. 2548 * 2549 * @type string|null $blockName Name of block. 2550 * @type array $attrs Attributes from block comment delimiters. 2551 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 2552 * have the same structure as this one. 2553 * @type string $innerHTML HTML from inside block comment delimiters. 2554 * @type array $innerContent List of string fragments and null markers where 2555 * inner blocks were found. 2556 * } 2557 * @return string String of rendered HTML. 2558 */ 2559 function render_block( $parsed_block ) { 2560 global $post; 2561 $parent_block = null; 2562 2563 /** 2564 * Allows render_block() to be short-circuited, by returning a non-null value. 2565 * 2566 * @since 5.1.0 2567 * @since 5.9.0 The `$parent_block` parameter was added. 2568 * 2569 * @param string|null $pre_render The pre-rendered content. Default null. 2570 * @param array $parsed_block { 2571 * An associative array of the block being rendered. See WP_Block_Parser_Block. 2572 * 2573 * @type string|null $blockName Name of block. 2574 * @type array $attrs Attributes from block comment delimiters. 2575 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 2576 * have the same structure as this one. 2577 * @type string $innerHTML HTML from inside block comment delimiters. 2578 * @type array $innerContent List of string fragments and null markers where 2579 * inner blocks were found. 2580 * } 2581 * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. 2582 */ 2583 $pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block ); 2584 if ( ! is_null( $pre_render ) ) { 2585 return $pre_render; 2586 } 2587 2588 $source_block = $parsed_block; 2589 2590 /** 2591 * Filters the block being rendered in render_block(), before it's processed. 2592 * 2593 * @since 5.1.0 2594 * @since 5.9.0 The `$parent_block` parameter was added. 2595 * 2596 * @param array $parsed_block { 2597 * An associative array of the block being rendered. See WP_Block_Parser_Block. 2598 * 2599 * @type string|null $blockName Name of block. 2600 * @type array $attrs Attributes from block comment delimiters. 2601 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 2602 * have the same structure as this one. 2603 * @type string $innerHTML HTML from inside block comment delimiters. 2604 * @type array $innerContent List of string fragments and null markers where 2605 * inner blocks were found. 2606 * } 2607 * @param array $source_block { 2608 * An un-modified copy of `$parsed_block`, as it appeared in the source content. 2609 * See WP_Block_Parser_Block. 2610 * 2611 * @type string|null $blockName Name of block. 2612 * @type array $attrs Attributes from block comment delimiters. 2613 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 2614 * have the same structure as this one. 2615 * @type string $innerHTML HTML from inside block comment delimiters. 2616 * @type array $innerContent List of string fragments and null markers where 2617 * inner blocks were found. 2618 * } 2619 * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. 2620 */ 2621 $parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block ); 2622 2623 $context = array(); 2624 2625 if ( $post instanceof WP_Post ) { 2626 $context['postId'] = $post->ID; 2627 2628 /* 2629 * The `postType` context is largely unnecessary server-side, since the ID 2630 * is usually sufficient on its own. That being said, since a block's 2631 * manifest is expected to be shared between the server and the client, 2632 * it should be included to consistently fulfill the expectation. 2633 */ 2634 $context['postType'] = $post->post_type; 2635 } 2636 2637 /** 2638 * Filters the default context provided to a rendered block. 2639 * 2640 * @since 5.5.0 2641 * @since 5.9.0 The `$parent_block` parameter was added. 2642 * 2643 * @param array $context Default context. 2644 * @param array $parsed_block { 2645 * An associative array of the block being rendered. See WP_Block_Parser_Block. 2646 * 2647 * @type string|null $blockName Name of block. 2648 * @type array $attrs Attributes from block comment delimiters. 2649 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 2650 * have the same structure as this one. 2651 * @type string $innerHTML HTML from inside block comment delimiters. 2652 * @type array $innerContent List of string fragments and null markers where 2653 * inner blocks were found. 2654 * } 2655 * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. 2656 */ 2657 $context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block ); 2658 2659 $block = new WP_Block( $parsed_block, $context ); 2660 2661 return $block->render(); 2662 } 2663 2664 /** 2665 * Parses blocks out of a content string. 2666 * 2667 * Given an HTML document, this function fully-parses block content, producing 2668 * a tree of blocks and their contents, as well as top-level non-block content, 2669 * which will appear as a block with no `blockName`. 2670 * 2671 * This function can be memory heavy for certain documents, particularly those 2672 * with deeply-nested blocks or blocks with extensive attribute values. Further, 2673 * this function must parse an entire document in one atomic operation. 2674 * 2675 * If the entire parsed document is not necessary, consider using {@see WP_Block_Processor} 2676 * instead, as it provides a streaming and low-overhead interface for finding blocks. 2677 * 2678 * @since 5.0.0 2679 * 2680 * @param string $content Post content. 2681 * @return array[] { 2682 * Array of block structures. 2683 * 2684 * @type array ...$0 { 2685 * An associative array of a single parsed block object. See WP_Block_Parser_Block. 2686 * 2687 * @type string|null $blockName Name of block. 2688 * @type array $attrs Attributes from block comment delimiters. 2689 * @type array[] $innerBlocks List of inner blocks. An array of arrays that 2690 * have the same structure as this one. 2691 * @type string $innerHTML HTML from inside block comment delimiters. 2692 * @type array $innerContent List of string fragments and null markers where 2693 * inner blocks were found. 2694 * } 2695 * } 2696 */ 2697 function parse_blocks( $content ) { 2698 /** 2699 * Filter to allow plugins to replace the server-side block parser. 2700 * 2701 * @since 5.0.0 2702 * 2703 * @param string $parser_class Name of block parser class. 2704 */ 2705 $parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' ); 2706 2707 $parser = new $parser_class(); 2708 return $parser->parse( $content ); 2709 } 2710 2711 /** 2712 * Parses dynamic blocks out of `post_content` and re-renders them. 2713 * 2714 * @since 5.0.0 2715 * 2716 * @param string $content Post content. 2717 * @return string Updated post content. 2718 */ 2719 function do_blocks( $content ) { 2720 $blocks = parse_blocks( $content ); 2721 $top_level_block_count = count( $blocks ); 2722 $output = ''; 2723 2724 /** 2725 * Parsed blocks consist of a list of top-level blocks. Those top-level 2726 * blocks may themselves contain nested inner blocks. However, every 2727 * top-level block is rendered independently, meaning there are no data 2728 * dependencies between them. 2729 * 2730 * Ideally, therefore, the parser would only need to parse one complete 2731 * top-level block at a time, render it, and move on. Unfortunately, this 2732 * is not possible with {@see \parse_blocks()} because it must parse the 2733 * entire given document at once. 2734 * 2735 * While the current implementation prevents this optimization, it’s still 2736 * possible to reduce the peak memory use when calls to `render_block()` 2737 * on those top-level blocks are memory-heavy (which many of them are). 2738 * By setting each parsed block to `NULL` after rendering it, any memory 2739 * allocated during the render will be freed and reused for the next block. 2740 * Before making this change, that memory was retained and would lead to 2741 * out-of-memory crashes for certain posts that now run with this change. 2742 */ 2743 for ( $i = 0; $i < $top_level_block_count; $i++ ) { 2744 $output .= render_block( $blocks[ $i ] ); 2745 $blocks[ $i ] = null; 2746 } 2747 2748 // If there are blocks in this content, we shouldn't run wpautop() on it later. 2749 $priority = has_filter( 'the_content', 'wpautop' ); 2750 if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) { 2751 remove_filter( 'the_content', 'wpautop', $priority ); 2752 add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 ); 2753 } 2754 2755 return $output; 2756 } 2757 2758 /** 2759 * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards, 2760 * for subsequent `the_content` usage. 2761 * 2762 * @since 5.0.0 2763 * @access private 2764 * 2765 * @param string $content The post content running through this filter. 2766 * @return string The unmodified content. 2767 */ 2768 function _restore_wpautop_hook( $content ) { 2769 $current_priority = has_filter( 'the_content', '_restore_wpautop_hook' ); 2770 2771 add_filter( 'the_content', 'wpautop', $current_priority - 1 ); 2772 remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority ); 2773 2774 return $content; 2775 } 2776 2777 /** 2778 * Applies standard content filters similar to the 'the_content' filter. 2779 * 2780 * This function runs the typical content processing filters that WordPress 2781 * applies to post content, useful for blocks that render nested content. 2782 * 2783 * @since 7.1.0 2784 * @access private 2785 * 2786 * @global WP_Embed $wp_embed WordPress Embed object. 2787 * 2788 * @param string $content The content to process. 2789 * @param string $context Optional. Context identifier for wp_filter_content_tags(). 2790 * Default empty string. 2791 * @param array|null $seen_ids Optional. Reference to an array tracking seen IDs for 2792 * recursion prevention. Default null. 2793 * @param string|null $id Optional. Unique identifier for this content, used with 2794 * $seen_ids. Default null. 2795 * @return string The processed content. 2796 */ 2797 function _wp_apply_block_content_filters( $content, $context = '', &$seen_ids = null, $id = null ) { 2798 $content = shortcode_unautop( $content ); 2799 $content = do_shortcode( $content ); 2800 2801 if ( null !== $seen_ids && null !== $id ) { 2802 $seen_ids[ $id ] = true; 2803 } 2804 2805 try { 2806 $content = do_blocks( $content ); 2807 } finally { 2808 if ( null !== $seen_ids && null !== $id ) { 2809 unset( $seen_ids[ $id ] ); 2810 } 2811 } 2812 2813 $content = wptexturize( $content ); 2814 $content = convert_smilies( $content ); 2815 $content = wp_filter_content_tags( $content, $context ); 2816 2817 global $wp_embed; 2818 $content = $wp_embed->autoembed( $content ); 2819 2820 return $content; 2821 } 2822 2823 /** 2824 * Returns the current version of the block format that the content string is using. 2825 * 2826 * If the string doesn't contain blocks, it returns 0. 2827 * 2828 * @since 5.0.0 2829 * 2830 * @param string $content Content to test. 2831 * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise. 2832 * 2833 * @phpstan-return ( $content is '' ? 0 : 0|1 ) 2834 */ 2835 function block_version( $content ) { 2836 return has_blocks( $content ) ? 1 : 0; 2837 } 2838 2839 /** 2840 * Registers a new block style. 2841 * 2842 * @since 5.3.0 2843 * @since 6.6.0 Added support for registering styles for multiple block types. 2844 * 2845 * @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/ 2846 * 2847 * @param string|string[] $block_name Block type name including namespace or array of namespaced block type names. 2848 * @param array $style_properties Array containing the properties of the style name, label, 2849 * style_handle (name of the stylesheet to be enqueued), 2850 * inline_style (string containing the CSS to be added), 2851 * style_data (theme.json-like array to generate CSS from). 2852 * See WP_Block_Styles_Registry::register(). 2853 * @return bool True if the block style was registered with success and false otherwise. 2854 */ 2855 function register_block_style( $block_name, $style_properties ) { 2856 return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties ); 2857 } 2858 2859 /** 2860 * Unregisters a block style. 2861 * 2862 * @since 5.3.0 2863 * 2864 * @param string $block_name Block type name including namespace. 2865 * @param string $block_style_name Block style name. 2866 * @return bool True if the block style was unregistered with success and false otherwise. 2867 */ 2868 function unregister_block_style( $block_name, $block_style_name ) { 2869 return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name ); 2870 } 2871 2872 /** 2873 * Checks whether the current block type supports the feature requested. 2874 * 2875 * @since 5.8.0 2876 * @since 6.4.0 The `$feature` parameter now supports a string. 2877 * 2878 * @param WP_Block_Type|null $block_type Block type to check for support. 2879 * @param string|array $feature Feature slug, or path to a specific feature to check support for. 2880 * @param mixed $default_value Optional. Fallback value for feature support. Default false. 2881 * @return bool Whether the feature is supported. 2882 */ 2883 function block_has_support( $block_type, $feature, $default_value = false ) { 2884 $block_support = $default_value; 2885 if ( $block_type instanceof WP_Block_Type ) { 2886 if ( is_array( $feature ) && count( $feature ) === 1 ) { 2887 $feature = $feature[0]; 2888 } 2889 2890 if ( is_array( $feature ) ) { 2891 $block_support = _wp_array_get( $block_type->supports, $feature, $default_value ); 2892 } elseif ( isset( $block_type->supports[ $feature ] ) ) { 2893 $block_support = $block_type->supports[ $feature ]; 2894 } 2895 } 2896 2897 return true === $block_support || is_array( $block_support ); 2898 } 2899 2900 /** 2901 * Converts typography keys declared under `supports.*` to `supports.typography.*`. 2902 * 2903 * Displays a `_doing_it_wrong()` notice when a block using the older format is detected. 2904 * 2905 * @since 5.8.0 2906 * 2907 * @param array $metadata Metadata for registering a block type. 2908 * @return array Filtered metadata for registering a block type. 2909 */ 2910 function wp_migrate_old_typography_shape( $metadata ) { 2911 if ( ! isset( $metadata['supports'] ) ) { 2912 return $metadata; 2913 } 2914 2915 $typography_keys = array( 2916 '__experimentalFontFamily', 2917 '__experimentalFontStyle', 2918 '__experimentalFontWeight', 2919 '__experimentalLetterSpacing', 2920 '__experimentalTextDecoration', 2921 '__experimentalTextTransform', 2922 'fontSize', 2923 'lineHeight', 2924 ); 2925 2926 foreach ( $typography_keys as $typography_key ) { 2927 $support_for_key = $metadata['supports'][ $typography_key ] ?? null; 2928 2929 if ( null !== $support_for_key ) { 2930 _doing_it_wrong( 2931 'register_block_type_from_metadata()', 2932 sprintf( 2933 /* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */ 2934 __( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ), 2935 $metadata['name'], 2936 "<code>$typography_key</code>", 2937 '<code>block.json</code>', 2938 "<code>supports.$typography_key</code>", 2939 "<code>supports.typography.$typography_key</code>" 2940 ), 2941 '5.8.0' 2942 ); 2943 2944 _wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key ); 2945 unset( $metadata['supports'][ $typography_key ] ); 2946 } 2947 } 2948 2949 return $metadata; 2950 } 2951 2952 /** 2953 * Helper function that constructs a WP_Query args array from 2954 * a `Query` block properties. 2955 * 2956 * It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks. 2957 * 2958 * @since 5.8.0 2959 * @since 6.1.0 Added `query_loop_block_query_vars` filter and `parents` support in query. 2960 * @since 6.7.0 Added support for the `format` property in query. 2961 * @since 7.0.0 Updated `taxQuery` structure. 2962 * @since 7.1.0 Added support for the `excludeCurrent` property in query. 2963 * 2964 * @param WP_Block $block Block instance. 2965 * @param int $page Current query's page. 2966 * @return array Returns the constructed WP_Query arguments. 2967 */ 2968 function build_query_vars_from_query_block( $block, $page ) { 2969 $query = array( 2970 'post_type' => 'post', 2971 'order' => 'DESC', 2972 'orderby' => 'date', 2973 'post__not_in' => array(), 2974 'tax_query' => array(), 2975 ); 2976 2977 if ( isset( $block->context['query'] ) ) { 2978 if ( ! empty( $block->context['query']['postType'] ) ) { 2979 $post_type_param = $block->context['query']['postType']; 2980 if ( is_post_type_viewable( $post_type_param ) ) { 2981 $query['post_type'] = $post_type_param; 2982 } 2983 } 2984 if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) { 2985 $sticky = get_option( 'sticky_posts' ); 2986 if ( 'only' === $block->context['query']['sticky'] ) { 2987 /* 2988 * Passing an empty array to post__in will return have_posts() as true (and all posts will be returned). 2989 * Logic should be used beforehand to determine if WP_Query should be used in the event that the array 2990 * being passed to post__in is empty. 2991 * 2992 * @link https://core.trac.wordpress.org/ticket/28099 2993 */ 2994 $query['post__in'] = ! empty( $sticky ) ? $sticky : array( 0 ); 2995 $query['ignore_sticky_posts'] = 1; 2996 } elseif ( 'exclude' === $block->context['query']['sticky'] ) { 2997 $query['post__not_in'] = array_merge( $query['post__not_in'], $sticky ); 2998 } elseif ( 'ignore' === $block->context['query']['sticky'] ) { 2999 $query['ignore_sticky_posts'] = 1; 3000 } 3001 } 3002 if ( ! empty( $block->context['query']['exclude'] ) ) { 3003 $excluded_post_ids = array_map( 'intval', $block->context['query']['exclude'] ); 3004 $excluded_post_ids = array_filter( $excluded_post_ids ); 3005 $query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids ); 3006 } 3007 if ( ! empty( $block->context['query']['excludeCurrent'] ) ) { 3008 $current_post_id = get_the_ID(); 3009 if ( $current_post_id ) { 3010 $query['post__not_in'][] = $current_post_id; 3011 } 3012 } 3013 if ( 3014 isset( $block->context['query']['perPage'] ) && 3015 is_numeric( $block->context['query']['perPage'] ) 3016 ) { 3017 $per_page = absint( $block->context['query']['perPage'] ); 3018 $offset = 0; 3019 3020 if ( 3021 isset( $block->context['query']['offset'] ) && 3022 is_numeric( $block->context['query']['offset'] ) 3023 ) { 3024 $offset = absint( $block->context['query']['offset'] ); 3025 } 3026 3027 $query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset; 3028 $query['posts_per_page'] = $per_page; 3029 } 3030 // Migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility. 3031 if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) { 3032 $tax_query_back_compat = array(); 3033 if ( ! empty( $block->context['query']['categoryIds'] ) ) { 3034 $tax_query_back_compat[] = array( 3035 'taxonomy' => 'category', 3036 'terms' => array_filter( array_map( 'intval', $block->context['query']['categoryIds'] ) ), 3037 'include_children' => false, 3038 ); 3039 } 3040 if ( ! empty( $block->context['query']['tagIds'] ) ) { 3041 $tax_query_back_compat[] = array( 3042 'taxonomy' => 'post_tag', 3043 'terms' => array_filter( array_map( 'intval', $block->context['query']['tagIds'] ) ), 3044 'include_children' => false, 3045 ); 3046 } 3047 $query['tax_query'] = array_merge( $query['tax_query'], $tax_query_back_compat ); 3048 } 3049 3050 if ( ! empty( $block->context['query']['taxQuery'] ) && is_array( $block->context['query']['taxQuery'] ) ) { 3051 $tax_query_input = $block->context['query']['taxQuery']; 3052 $tax_query = array(); 3053 // If there are keys other than include/exclude, it's the old 3054 // format e.g. "taxQuery":{"category":[4]} 3055 if ( ! empty( array_diff( array_keys( $tax_query_input ), array( 'include', 'exclude' ) ) ) ) { 3056 foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) { 3057 if ( is_taxonomy_viewable( $taxonomy ) && ! empty( $terms ) ) { 3058 $tax_query[] = array( 3059 'taxonomy' => $taxonomy, 3060 'terms' => array_filter( array_map( 'intval', $terms ) ), 3061 'include_children' => false, 3062 ); 3063 } 3064 } 3065 } else { 3066 // This is the new format e.g. "taxQuery":{"include":{"category":[4]},"exclude":{"post_tag":[5]}} 3067 3068 // Helper function to build tax_query conditions from taxonomy terms. 3069 $build_conditions = static function ( $terms, string $operator = 'IN' ): array { 3070 $terms = (array) $terms; 3071 $conditions = array(); 3072 foreach ( $terms as $taxonomy => $tax_terms ) { 3073 if ( ! empty( $tax_terms ) && is_taxonomy_viewable( $taxonomy ) ) { 3074 $conditions[] = array( 3075 'taxonomy' => $taxonomy, 3076 'terms' => array_filter( array_map( 'intval', $tax_terms ) ), 3077 'operator' => $operator, 3078 'include_children' => false, 3079 ); 3080 } 3081 } 3082 return $conditions; 3083 }; 3084 3085 // Separate exclude from include terms. 3086 $exclude_terms = isset( $tax_query_input['exclude'] ) && is_array( $tax_query_input['exclude'] ) 3087 ? $tax_query_input['exclude'] 3088 : array(); 3089 $include_terms = isset( $tax_query_input['include'] ) && is_array( $tax_query_input['include'] ) 3090 ? $tax_query_input['include'] 3091 : array(); 3092 3093 $tax_query = array_merge( 3094 $build_conditions( $include_terms ), 3095 $build_conditions( $exclude_terms, 'NOT IN' ) 3096 ); 3097 } 3098 3099 if ( ! empty( $tax_query ) ) { 3100 // Merge with any existing `tax_query` conditions. 3101 $query['tax_query'] = array_merge( $query['tax_query'], $tax_query ); 3102 } 3103 } 3104 if ( ! empty( $block->context['query']['format'] ) && is_array( $block->context['query']['format'] ) ) { 3105 $formats = $block->context['query']['format']; 3106 /* 3107 * Validate that the format is either `standard` or a supported post format. 3108 * - First, add `standard` to the array of valid formats. 3109 * - Then, remove any invalid formats. 3110 */ 3111 $valid_formats = array_merge( array( 'standard' ), get_post_format_slugs() ); 3112 $formats = array_intersect( $formats, $valid_formats ); 3113 3114 /* 3115 * The relation needs to be set to `OR` since the request can contain 3116 * two separate conditions. The user may be querying for items that have 3117 * either the `standard` format or a specific format. 3118 */ 3119 $formats_query = array( 'relation' => 'OR' ); 3120 3121 /* 3122 * The default post format, `standard`, is not stored in the database. 3123 * If `standard` is part of the request, the query needs to exclude all post items that 3124 * have a format assigned. 3125 */ 3126 if ( in_array( 'standard', $formats, true ) ) { 3127 $formats_query[] = array( 3128 'taxonomy' => 'post_format', 3129 'field' => 'slug', 3130 'operator' => 'NOT EXISTS', 3131 ); 3132 // Remove the `standard` format, since it cannot be queried. 3133 unset( $formats[ array_search( 'standard', $formats, true ) ] ); 3134 } 3135 // Add any remaining formats to the formats query. 3136 if ( ! empty( $formats ) ) { 3137 // Add the `post-format-` prefix. 3138 $terms = array_map( 3139 static function ( $format ) { 3140 return "post-format-$format"; 3141 }, 3142 $formats 3143 ); 3144 $formats_query[] = array( 3145 'taxonomy' => 'post_format', 3146 'field' => 'slug', 3147 'terms' => $terms, 3148 'operator' => 'IN', 3149 ); 3150 } 3151 3152 /* 3153 * Add `$formats_query` to `$query`, as long as it contains more than one key: 3154 * If `$formats_query` only contains the initial `relation` key, there are no valid formats to query, 3155 * and the query should not be modified. 3156 */ 3157 if ( count( $formats_query ) > 1 ) { 3158 // Enable filtering by both post formats and other taxonomies by combining them with `AND`. 3159 if ( empty( $query['tax_query'] ) ) { 3160 $query['tax_query'] = $formats_query; 3161 } else { 3162 $query['tax_query'] = array( 3163 'relation' => 'AND', 3164 $query['tax_query'], 3165 $formats_query, 3166 ); 3167 } 3168 } 3169 } 3170 3171 if ( 3172 isset( $block->context['query']['order'] ) && 3173 in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true ) 3174 ) { 3175 $query['order'] = strtoupper( $block->context['query']['order'] ); 3176 } 3177 if ( isset( $block->context['query']['orderBy'] ) ) { 3178 $query['orderby'] = $block->context['query']['orderBy']; 3179 } 3180 if ( 3181 isset( $block->context['query']['author'] ) 3182 ) { 3183 if ( is_array( $block->context['query']['author'] ) ) { 3184 $query['author__in'] = array_filter( array_map( 'intval', $block->context['query']['author'] ) ); 3185 } elseif ( is_string( $block->context['query']['author'] ) ) { 3186 $query['author__in'] = array_filter( array_map( 'intval', explode( ',', $block->context['query']['author'] ) ) ); 3187 } elseif ( is_int( $block->context['query']['author'] ) && $block->context['query']['author'] > 0 ) { 3188 $query['author'] = $block->context['query']['author']; 3189 } 3190 } 3191 if ( ! empty( $block->context['query']['search'] ) ) { 3192 $query['s'] = $block->context['query']['search']; 3193 } 3194 if ( ! empty( $block->context['query']['parents'] ) && is_post_type_hierarchical( $query['post_type'] ) ) { 3195 $query['post_parent__in'] = array_unique( array_map( 'intval', $block->context['query']['parents'] ) ); 3196 } 3197 } 3198 3199 /** 3200 * Filters the arguments which will be passed to `WP_Query` for the Query Loop Block. 3201 * 3202 * Anything to this filter should be compatible with the `WP_Query` API to form 3203 * the query context which will be passed down to the Query Loop Block's children. 3204 * This can help, for example, to include additional settings or meta queries not 3205 * directly supported by the core Query Loop Block, and extend its capabilities. 3206 * 3207 * Please note that this will only influence the query that will be rendered on the 3208 * front-end. The editor preview is not affected by this filter. Also, worth noting 3209 * that the editor preview uses the REST API, so, ideally, one should aim to provide 3210 * attributes which are also compatible with the REST API, in order to be able to 3211 * implement identical queries on both sides. 3212 * 3213 * @since 6.1.0 3214 * 3215 * @param array $query Array containing parameters for `WP_Query` as parsed by the block context. 3216 * @param WP_Block $block Block instance. 3217 * @param int $page Current query's page. 3218 */ 3219 return apply_filters( 'query_loop_block_query_vars', $query, $block, $page ); 3220 } 3221 3222 /** 3223 * Helper function that returns the proper pagination arrow HTML for 3224 * `QueryPaginationNext` and `QueryPaginationPrevious` blocks based 3225 * on the provided `paginationArrow` from `QueryPagination` context. 3226 * 3227 * It's used in QueryPaginationNext and QueryPaginationPrevious blocks. 3228 * 3229 * @since 5.9.0 3230 * 3231 * @param WP_Block $block Block instance. 3232 * @param bool $is_next Flag for handling `next/previous` blocks. 3233 * @return string|null The pagination arrow HTML or null if there is none. 3234 * 3235 * @phpstan-return non-falsy-string|null 3236 */ 3237 function get_query_pagination_arrow( $block, $is_next ) { 3238 $arrow_map = array( 3239 'none' => '', 3240 'arrow' => array( 3241 'next' => '→', 3242 'previous' => '←', 3243 ), 3244 'chevron' => array( 3245 'next' => '»', 3246 'previous' => '«', 3247 ), 3248 ); 3249 if ( ! empty( $block->context['paginationArrow'] ) && array_key_exists( $block->context['paginationArrow'], $arrow_map ) && ! empty( $arrow_map[ $block->context['paginationArrow'] ] ) ) { 3250 $pagination_type = $is_next ? 'next' : 'previous'; 3251 $arrow_attribute = $block->context['paginationArrow']; 3252 $arrow = $arrow_map[ $block->context['paginationArrow'] ][ $pagination_type ]; 3253 $arrow_classes = "wp-block-query-pagination-$pagination_type-arrow is-arrow-$arrow_attribute"; 3254 return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>"; 3255 } 3256 return null; 3257 } 3258 3259 /** 3260 * Helper function that constructs a comment query vars array from the passed 3261 * block properties. 3262 * 3263 * It's used with the Comment Query Loop inner blocks. 3264 * 3265 * @since 6.0.0 3266 * 3267 * @param WP_Block $block Block instance. 3268 * @return array Returns the comment query parameters to use with the 3269 * WP_Comment_Query constructor. 3270 */ 3271 function build_comment_query_vars_from_block( $block ) { 3272 3273 $comment_args = array( 3274 'orderby' => 'comment_date_gmt', 3275 'order' => 'ASC', 3276 'status' => 'approve', 3277 'no_found_rows' => false, 3278 ); 3279 3280 if ( is_user_logged_in() ) { 3281 $comment_args['include_unapproved'] = array( get_current_user_id() ); 3282 } else { 3283 $unapproved_email = wp_get_unapproved_comment_author_email(); 3284 3285 if ( $unapproved_email ) { 3286 $comment_args['include_unapproved'] = array( $unapproved_email ); 3287 } 3288 } 3289 3290 if ( ! empty( $block->context['postId'] ) ) { 3291 $comment_args['post_id'] = (int) $block->context['postId']; 3292 } 3293 3294 if ( get_option( 'thread_comments' ) ) { 3295 $comment_args['hierarchical'] = 'threaded'; 3296 } else { 3297 $comment_args['hierarchical'] = false; 3298 } 3299 3300 if ( get_option( 'page_comments' ) === '1' || get_option( 'page_comments' ) === true ) { 3301 $per_page = get_option( 'comments_per_page' ); 3302 $default_page = get_option( 'default_comments_page' ); 3303 if ( $per_page > 0 ) { 3304 $comment_args['number'] = $per_page; 3305 3306 $page = (int) get_query_var( 'cpage' ); 3307 if ( $page ) { 3308 $comment_args['paged'] = $page; 3309 } elseif ( 'oldest' === $default_page ) { 3310 $comment_args['paged'] = 1; 3311 } elseif ( 'newest' === $default_page ) { 3312 $max_num_pages = (int) ( new WP_Comment_Query( $comment_args ) )->max_num_pages; 3313 if ( 0 !== $max_num_pages ) { 3314 $comment_args['paged'] = $max_num_pages; 3315 } 3316 } 3317 } 3318 } 3319 3320 return $comment_args; 3321 } 3322 3323 /** 3324 * Helper function that returns the proper pagination arrow HTML for 3325 * `CommentsPaginationNext` and `CommentsPaginationPrevious` blocks based on the 3326 * provided `paginationArrow` from `CommentsPagination` context. 3327 * 3328 * It's used in CommentsPaginationNext and CommentsPaginationPrevious blocks. 3329 * 3330 * @since 6.0.0 3331 * 3332 * @param WP_Block $block Block instance. 3333 * @param string $pagination_type Optional. Type of the arrow we will be rendering. 3334 * Accepts 'next' or 'previous'. Default 'next'. 3335 * @return string|null The pagination arrow HTML or null if there is none. 3336 * 3337 * @phpstan-return non-falsy-string|null 3338 */ 3339 function get_comments_pagination_arrow( $block, $pagination_type = 'next' ) { 3340 $arrow_map = array( 3341 'none' => '', 3342 'arrow' => array( 3343 'next' => '→', 3344 'previous' => '←', 3345 ), 3346 'chevron' => array( 3347 'next' => '»', 3348 'previous' => '«', 3349 ), 3350 ); 3351 if ( ! empty( $block->context['comments/paginationArrow'] ) && ! empty( $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ] ) ) { 3352 $arrow_attribute = $block->context['comments/paginationArrow']; 3353 $arrow = $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ]; 3354 $arrow_classes = "wp-block-comments-pagination-$pagination_type-arrow is-arrow-$arrow_attribute"; 3355 return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>"; 3356 } 3357 return null; 3358 } 3359 3360 /** 3361 * Strips all HTML from the content of footnotes, and sanitizes the ID. 3362 * 3363 * This function expects slashed data on the footnotes content. 3364 * 3365 * @access private 3366 * @since 6.3.2 3367 * 3368 * @param string $footnotes JSON-encoded string of an array containing the content and ID of each footnote. 3369 * @return string Filtered content without any HTML on the footnote content and with the sanitized ID. 3370 */ 3371 function _wp_filter_post_meta_footnotes( $footnotes ) { 3372 $footnotes_decoded = json_decode( $footnotes, true ); 3373 if ( ! is_array( $footnotes_decoded ) ) { 3374 return ''; 3375 } 3376 $footnotes_sanitized = array(); 3377 foreach ( $footnotes_decoded as $footnote ) { 3378 if ( ! empty( $footnote['content'] ) && ! empty( $footnote['id'] ) ) { 3379 $footnotes_sanitized[] = array( 3380 'id' => sanitize_key( $footnote['id'] ), 3381 'content' => wp_unslash( wp_filter_post_kses( wp_slash( $footnote['content'] ) ) ), 3382 ); 3383 } 3384 } 3385 return wp_json_encode( $footnotes_sanitized ); 3386 } 3387 3388 /** 3389 * Adds the filters for footnotes meta field. 3390 * 3391 * @access private 3392 * @since 6.3.2 3393 */ 3394 function _wp_footnotes_kses_init_filters() { 3395 add_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' ); 3396 } 3397 3398 /** 3399 * Removes the filters for footnotes meta field. 3400 * 3401 * @access private 3402 * @since 6.3.2 3403 */ 3404 function _wp_footnotes_remove_filters() { 3405 remove_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' ); 3406 } 3407 3408 /** 3409 * Registers the filter of footnotes meta field if the user does not have `unfiltered_html` capability. 3410 * 3411 * @access private 3412 * @since 6.3.2 3413 */ 3414 function _wp_footnotes_kses_init() { 3415 _wp_footnotes_remove_filters(); 3416 if ( ! current_user_can( 'unfiltered_html' ) ) { 3417 _wp_footnotes_kses_init_filters(); 3418 } 3419 } 3420 3421 /** 3422 * Initializes the filters for footnotes meta field when imported data should be filtered. 3423 * 3424 * This filter is the last one being executed on {@see 'force_filtered_html_on_import'}. 3425 * If the input of the filter is true, it means we are in an import situation and should 3426 * enable kses, independently of the user capabilities. So in that case we call 3427 * _wp_footnotes_kses_init_filters(). 3428 * 3429 * @access private 3430 * @since 6.3.2 3431 * 3432 * @param string $arg Input argument of the filter. 3433 * @return string Input argument of the filter. 3434 */ 3435 function _wp_footnotes_force_filtered_html_on_import_filter( $arg ) { 3436 // If `force_filtered_html_on_import` is true, we need to init the global styles kses filters. 3437 if ( $arg ) { 3438 _wp_footnotes_kses_init_filters(); 3439 } 3440 return $arg; 3441 } 3442 3443 /** 3444 * Exposes blocks with autoRegister flag for ServerSideRender in the editor. 3445 * 3446 * Detects blocks that have the autoRegister flag set in their supports 3447 * and passes them to JavaScript for auto-registration with ServerSideRender. 3448 * 3449 * @access private 3450 * @since 7.0.0 3451 */ 3452 function _wp_enqueue_auto_register_blocks() { 3453 $auto_register_blocks = array(); 3454 $registered_blocks = WP_Block_Type_Registry::get_instance()->get_all_registered(); 3455 3456 foreach ( $registered_blocks as $block_name => $block_type ) { 3457 if ( ! empty( $block_type->supports['autoRegister'] ) && ! empty( $block_type->render_callback ) ) { 3458 $auto_register_blocks[] = $block_name; 3459 } 3460 } 3461 3462 if ( ! empty( $auto_register_blocks ) ) { 3463 wp_add_inline_script( 3464 'wp-block-library', 3465 sprintf( 'window.__unstableAutoRegisterBlocks = %s;', wp_json_encode( $auto_register_blocks ) ), 3466 'before' 3467 ); 3468 } 3469 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Sun Nov 22 08:20:01 2026 | Cross-referenced by PHPXref |