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