[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> blocks.php (source)

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


Generated : Mon Aug 24 08:20:24 2026 Cross-referenced by PHPXref