[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> block-template-utils.php (source)

   1  <?php
   2  /**
   3   * Utilities used to fetch and create templates and template parts.
   4   *
   5   * @package WordPress
   6   * @since 5.8.0
   7   */
   8  
   9  // Define constants for supported wp_template_part_area taxonomy.
  10  if ( ! defined( 'WP_TEMPLATE_PART_AREA_HEADER' ) ) {
  11      define( 'WP_TEMPLATE_PART_AREA_HEADER', 'header' );
  12  }
  13  if ( ! defined( 'WP_TEMPLATE_PART_AREA_FOOTER' ) ) {
  14      define( 'WP_TEMPLATE_PART_AREA_FOOTER', 'footer' );
  15  }
  16  if ( ! defined( 'WP_TEMPLATE_PART_AREA_SIDEBAR' ) ) {
  17      define( 'WP_TEMPLATE_PART_AREA_SIDEBAR', 'sidebar' );
  18  }
  19  if ( ! defined( 'WP_TEMPLATE_PART_AREA_UNCATEGORIZED' ) ) {
  20      define( 'WP_TEMPLATE_PART_AREA_UNCATEGORIZED', 'uncategorized' );
  21  }
  22  
  23  /**
  24   * For backward compatibility reasons,
  25   * block themes might be using block-templates or block-template-parts,
  26   * this function ensures we fallback to these folders properly.
  27   *
  28   * @since 5.9.0
  29   *
  30   * @param string $theme_stylesheet The stylesheet. Default is to leverage the main theme root.
  31   *
  32   * @return string[] {
  33   *     Folder names used by block themes.
  34   *
  35   *     @type string $wp_template      Theme-relative directory name for block templates.
  36   *     @type string $wp_template_part Theme-relative directory name for block template parts.
  37   * }
  38   */
  39  function get_block_theme_folders( $theme_stylesheet = null ) {
  40      $theme = wp_get_theme( (string) $theme_stylesheet );
  41      if ( ! $theme->exists() ) {
  42          // Return the default folders if the theme doesn't exist.
  43          return array(
  44              'wp_template'      => 'templates',
  45              'wp_template_part' => 'parts',
  46          );
  47      }
  48      return $theme->get_block_template_folders();
  49  }
  50  
  51  /**
  52   * Returns a filtered list of allowed area values for template parts.
  53   *
  54   * @since 5.9.0
  55   *
  56   * @return array[] {
  57   *     The allowed template part area values.
  58   *
  59   *     @type array ...$0 {
  60   *         Data for the allowed template part area.
  61   *
  62   *         @type string $area        Template part area name.
  63   *         @type string $label       Template part area label.
  64   *         @type string $description Template part area description.
  65   *         @type string $icon        Template part area icon.
  66   *         @type string $area_tag    Template part area tag.
  67   *     }
  68   * }
  69   */
  70  function get_allowed_block_template_part_areas() {
  71      $default_area_definitions = array(
  72          array(
  73              'area'        => WP_TEMPLATE_PART_AREA_UNCATEGORIZED,
  74              'label'       => _x( 'General', 'template part area' ),
  75              'description' => __(
  76                  'General templates often perform a specific role like displaying post content, and are not tied to any particular area.'
  77              ),
  78              'icon'        => 'layout',
  79              'area_tag'    => 'div',
  80          ),
  81          array(
  82              'area'        => WP_TEMPLATE_PART_AREA_HEADER,
  83              'label'       => _x( 'Header', 'template part area' ),
  84              'description' => __(
  85                  'The Header template defines a page area that typically contains a title, logo, and main navigation.'
  86              ),
  87              'icon'        => 'header',
  88              'area_tag'    => 'header',
  89          ),
  90          array(
  91              'area'        => WP_TEMPLATE_PART_AREA_FOOTER,
  92              'label'       => _x( 'Footer', 'template part area' ),
  93              'description' => __(
  94                  'The Footer template defines a page area that typically contains site credits, social links, or any other combination of blocks.'
  95              ),
  96              'icon'        => 'footer',
  97              'area_tag'    => 'footer',
  98          ),
  99      );
 100  
 101      /**
 102       * Filters the list of allowed template part area values.
 103       *
 104       * @since 5.9.0
 105       *
 106       * @param array[] $default_area_definitions {
 107       *     The allowed template part area values.
 108       *
 109       *     @type array ...$0 {
 110       *         Data for the template part area.
 111       *
 112       *         @type string $area        Template part area name.
 113       *         @type string $label       Template part area label.
 114       *         @type string $description Template part area description.
 115       *         @type string $icon        Template part area icon.
 116       *         @type string $area_tag    Template part area tag.
 117       *     }
 118       * }
 119       */
 120      return apply_filters( 'default_wp_template_part_areas', $default_area_definitions );
 121  }
 122  
 123  
 124  /**
 125   * Returns a filtered list of default template types, containing their
 126   * localized titles and descriptions.
 127   *
 128   * @since 5.9.0
 129   *
 130   * @return array[] {
 131   *     The default template types.
 132   *
 133   *     @type array ...$0 {
 134   *         Data for the template type.
 135   *
 136   *         @type string $title       Template type title.
 137   *         @type string $description Template type description.
 138   *    }
 139   * }
 140   */
 141  function get_default_block_template_types() {
 142      $default_template_types = array(
 143          'index'          => array(
 144              'title'       => _x( 'Index', 'Template name' ),
 145              'description' => __( 'Used as a fallback template for all pages when a more specific template is not defined.' ),
 146          ),
 147          'home'           => array(
 148              'title'       => _x( 'Blog Home', 'Template name' ),
 149              'description' => __( 'Displays the latest posts as either the site homepage or as the "Posts page" as defined under reading settings. If it exists, the Front Page template overrides this template when posts are shown on the homepage.' ),
 150          ),
 151          'front-page'     => array(
 152              'title'       => _x( 'Front Page', 'Template name' ),
 153              'description' => __( 'Displays your site\'s homepage, whether it is set to display latest posts or a static page. The Front Page template takes precedence over all templates.' ),
 154          ),
 155          'singular'       => array(
 156              'title'       => _x( 'Single Entries', 'Template name' ),
 157              'description' => __( 'Displays any single entry, such as a post or a page. This template will serve as a fallback when a more specific template (e.g. Single Post, Page, or Attachment) cannot be found.' ),
 158          ),
 159          'single'         => array(
 160              'title'       => _x( 'Single Posts', 'Template name' ),
 161              'description' => __( 'Displays a single post on your website unless a custom template has been applied to that post or a dedicated template exists.' ),
 162          ),
 163          'page'           => array(
 164              'title'       => _x( 'Pages', 'Template name' ),
 165              'description' => __( 'Displays a static page unless a custom template has been applied to that page or a dedicated template exists.' ),
 166          ),
 167          'archive'        => array(
 168              'title'       => _x( 'All Archives', 'Template name' ),
 169              'description' => __( 'Displays any archive, including posts by a single author, category, tag, taxonomy, custom post type, and date. This template will serve as a fallback when more specific templates (e.g. Category or Tag) cannot be found.' ),
 170          ),
 171          'author'         => array(
 172              'title'       => _x( 'Author Archives', 'Template name' ),
 173              'description' => __( 'Displays a single author\'s post archive. This template will serve as a fallback when a more specific template (e.g. Author: Admin) cannot be found.' ),
 174          ),
 175          'category'       => array(
 176              'title'       => _x( 'Category Archives', 'Template name' ),
 177              'description' => __( 'Displays a post category archive. This template will serve as a fallback when a more specific template (e.g. Category: Recipes) cannot be found.' ),
 178          ),
 179          'taxonomy'       => array(
 180              'title'       => _x( 'Taxonomy', 'Template name' ),
 181              'description' => __( 'Displays a custom taxonomy archive. Like categories and tags, taxonomies have terms which you use to classify things. For example: a taxonomy named "Art" can have multiple terms, such as "Modern" and "18th Century." This template will serve as a fallback when a more specific template (e.g. Taxonomy: Art) cannot be found.' ),
 182          ),
 183          'date'           => array(
 184              'title'       => _x( 'Date Archives', 'Template name' ),
 185              'description' => __( 'Displays a post archive when a specific date is visited (e.g., example.com/2023/).' ),
 186          ),
 187          'tag'            => array(
 188              'title'       => _x( 'Tag Archives', 'Template name' ),
 189              'description' => __( 'Displays a post tag archive. This template will serve as a fallback when a more specific template (e.g. Tag: Pizza) cannot be found.' ),
 190          ),
 191          'attachment'     => array(
 192              'title'       => __( 'Attachment Pages' ),
 193              'description' => __( 'Displays when a visitor views the dedicated page that exists for any media attachment.' ),
 194          ),
 195          'search'         => array(
 196              'title'       => _x( 'Search Results', 'Template name' ),
 197              'description' => __( 'Displays when a visitor performs a search on your website.' ),
 198          ),
 199          'privacy-policy' => array(
 200              'title'       => __( 'Privacy Policy' ),
 201              'description' => __( 'Displays your site\'s Privacy Policy page.' ),
 202          ),
 203          '404'            => array(
 204              'title'       => _x( 'Page: 404', 'Template name' ),
 205              'description' => __( 'Displays when a visitor views a non-existent page, such as a dead link or a mistyped URL.' ),
 206          ),
 207      );
 208  
 209      /**
 210       * Filters the list of default template types.
 211       *
 212       * @since 5.9.0
 213       *
 214       * @param array[] $default_template_types {
 215       *     The default template types.
 216       *
 217       *     @type array ...$0 {
 218       *         Data for the template type.
 219       *
 220       *         @type string $title       Template type title.
 221       *         @type string $description Template type description.
 222       *    }
 223       * }
 224       */
 225      return apply_filters( 'default_template_types', $default_template_types );
 226  }
 227  
 228  /**
 229   * Checks whether the input 'area' is a supported value.
 230   * Returns the input if supported, otherwise returns the 'uncategorized' value.
 231   *
 232   * @since 5.9.0
 233   * @access private
 234   *
 235   * @param string $type Template part area name.
 236   * @return string Input if supported, else the uncategorized value.
 237   */
 238  function _filter_block_template_part_area( $type ) {
 239      $allowed_areas = array_map(
 240          static function ( $item ) {
 241              return $item['area'];
 242          },
 243          get_allowed_block_template_part_areas()
 244      );
 245      if ( in_array( $type, $allowed_areas, true ) ) {
 246          return $type;
 247      }
 248  
 249      $warning_message = sprintf(
 250          /* translators: %1$s: Template area type, %2$s: the uncategorized template area value. */
 251          __( '"%1$s" is not a supported wp_template_part area value and has been added as "%2$s".' ),
 252          $type,
 253          WP_TEMPLATE_PART_AREA_UNCATEGORIZED
 254      );
 255      wp_trigger_error( __FUNCTION__, $warning_message );
 256      return WP_TEMPLATE_PART_AREA_UNCATEGORIZED;
 257  }
 258  
 259  /**
 260   * Finds all nested template part file paths in a theme's directory.
 261   *
 262   * @since 5.9.0
 263   * @access private
 264   *
 265   * @param string $base_directory The theme's file path.
 266   * @return string[] A list of paths to all template part files.
 267   */
 268  function _get_block_templates_paths( $base_directory ) {
 269      static $template_path_list = array();
 270      if ( isset( $template_path_list[ $base_directory ] ) ) {
 271          return $template_path_list[ $base_directory ];
 272      }
 273      $path_list = array();
 274      if ( is_dir( $base_directory ) ) {
 275          $nested_files      = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base_directory ) );
 276          $nested_html_files = new RegexIterator( $nested_files, '/^.+\.html$/i', RecursiveRegexIterator::GET_MATCH );
 277          foreach ( $nested_html_files as $path => $file ) {
 278              $path_list[] = $path;
 279          }
 280      }
 281      $template_path_list[ $base_directory ] = $path_list;
 282      return $path_list;
 283  }
 284  
 285  /**
 286   * Retrieves the template file from the theme for a given slug.
 287   *
 288   * @since 5.9.0
 289   * @access private
 290   *
 291   * @param string $template_type Template type. Either 'wp_template' or 'wp_template_part'.
 292   * @param string $slug          Template slug.
 293   * @return array|null {
 294   *     Array with template metadata if $template_type is one of 'wp_template' or 'wp_template_part',
 295   *     null otherwise.
 296   *
 297   *     @type string   $slug      Template slug.
 298   *     @type string   $path      Template file path.
 299   *     @type string   $theme     Theme slug.
 300   *     @type string   $type      Template type.
 301   *     @type string   $area      Template area. Only for 'wp_template_part'.
 302   *     @type string   $title     Optional. Template title.
 303   *     @type string[] $postTypes Optional. List of post types that the template supports. Only for 'wp_template'.
 304   * }
 305   */
 306  function _get_block_template_file( $template_type, $slug ) {
 307      if ( 'wp_template' !== $template_type && 'wp_template_part' !== $template_type ) {
 308          return null;
 309      }
 310  
 311      $themes = array(
 312          get_stylesheet() => get_stylesheet_directory(),
 313          get_template()   => get_template_directory(),
 314      );
 315      foreach ( $themes as $theme_slug => $theme_dir ) {
 316          $template_base_paths = get_block_theme_folders( $theme_slug );
 317          $file_path           = $theme_dir . '/' . $template_base_paths[ $template_type ] . '/' . $slug . '.html';
 318          if ( file_exists( $file_path ) ) {
 319              $new_template_item = array(
 320                  'slug'  => $slug,
 321                  'path'  => $file_path,
 322                  'theme' => $theme_slug,
 323                  'type'  => $template_type,
 324              );
 325  
 326              if ( 'wp_template_part' === $template_type ) {
 327                  return _add_block_template_part_area_info( $new_template_item );
 328              }
 329  
 330              if ( 'wp_template' === $template_type ) {
 331                  return _add_block_template_info( $new_template_item );
 332              }
 333  
 334              return $new_template_item;
 335          }
 336      }
 337  
 338      return null;
 339  }
 340  
 341  /**
 342   * Retrieves the template files from the theme.
 343   *
 344   * @since 5.9.0
 345   * @since 6.3.0 Added the `$query` parameter.
 346   * @access private
 347   *
 348   * @param string $template_type Template type. Either 'wp_template' or 'wp_template_part'.
 349   * @param array  $query {
 350   *     Arguments to retrieve templates. Optional, empty by default.
 351   *
 352   *     @type string[] $slug__in     List of slugs to include.
 353   *     @type string[] $slug__not_in List of slugs to skip.
 354   *     @type string   $area         A 'wp_template_part_area' taxonomy value to filter by (for 'wp_template_part' template type only).
 355   *     @type string   $post_type    Post type to get the templates for.
 356   * }
 357   *
 358   * @return array|null Template files on success, null if `$template_type` is not matched.
 359   */
 360  function _get_block_templates_files( $template_type, $query = array() ) {
 361      if ( 'wp_template' !== $template_type && 'wp_template_part' !== $template_type ) {
 362          return null;
 363      }
 364  
 365      $default_template_types = array();
 366      if ( 'wp_template' === $template_type ) {
 367          $default_template_types = get_default_block_template_types();
 368      }
 369  
 370      // Prepare metadata from $query.
 371      $slugs_to_include = isset( $query['slug__in'] ) ? $query['slug__in'] : array();
 372      $slugs_to_skip    = isset( $query['slug__not_in'] ) ? $query['slug__not_in'] : array();
 373      $area             = isset( $query['area'] ) ? $query['area'] : null;
 374      $post_type        = isset( $query['post_type'] ) ? $query['post_type'] : '';
 375  
 376      $stylesheet = get_stylesheet();
 377      $template   = get_template();
 378      $themes     = array(
 379          $stylesheet => get_stylesheet_directory(),
 380      );
 381      // Add the parent theme if it's not the same as the current theme.
 382      if ( $stylesheet !== $template ) {
 383          $themes[ $template ] = get_template_directory();
 384      }
 385      $template_files = array();
 386      foreach ( $themes as $theme_slug => $theme_dir ) {
 387          $template_base_paths  = get_block_theme_folders( $theme_slug );
 388          $theme_template_files = _get_block_templates_paths( $theme_dir . '/' . $template_base_paths[ $template_type ] );
 389          foreach ( $theme_template_files as $template_file ) {
 390              $template_base_path = $template_base_paths[ $template_type ];
 391              $template_slug      = substr(
 392                  $template_file,
 393                  // Starting position of slug.
 394                  strpos( $template_file, $template_base_path . DIRECTORY_SEPARATOR ) + 1 + strlen( $template_base_path ),
 395                  // Subtract ending '.html'.
 396                  -5
 397              );
 398  
 399              // Skip this item if its slug doesn't match any of the slugs to include.
 400              if ( ! empty( $slugs_to_include ) && ! in_array( $template_slug, $slugs_to_include, true ) ) {
 401                  continue;
 402              }
 403  
 404              // Skip this item if its slug matches any of the slugs to skip.
 405              if ( ! empty( $slugs_to_skip ) && in_array( $template_slug, $slugs_to_skip, true ) ) {
 406                  continue;
 407              }
 408  
 409              /*
 410               * The child theme items (stylesheet) are processed before the parent theme's (template).
 411               * If a child theme defines a template, prevent the parent template from being added to the list as well.
 412               */
 413              if ( isset( $template_files[ $template_slug ] ) ) {
 414                  continue;
 415              }
 416  
 417              $new_template_item = array(
 418                  'slug'  => $template_slug,
 419                  'path'  => $template_file,
 420                  'theme' => $theme_slug,
 421                  'type'  => $template_type,
 422              );
 423  
 424              if ( 'wp_template_part' === $template_type ) {
 425                  $candidate = _add_block_template_part_area_info( $new_template_item );
 426                  if ( ! isset( $area ) || ( isset( $area ) && $area === $candidate['area'] ) ) {
 427                      $template_files[ $template_slug ] = $candidate;
 428                  }
 429              }
 430  
 431              if ( 'wp_template' === $template_type ) {
 432                  $candidate = _add_block_template_info( $new_template_item );
 433                  $is_custom = ! isset( $default_template_types[ $candidate['slug'] ] );
 434  
 435                  if (
 436                      ! $post_type ||
 437                      ( $post_type && isset( $candidate['postTypes'] ) && in_array( $post_type, $candidate['postTypes'], true ) )
 438                  ) {
 439                      $template_files[ $template_slug ] = $candidate;
 440                  }
 441  
 442                  // The custom templates with no associated post types are available for all post types.
 443                  if ( $post_type && ! isset( $candidate['postTypes'] ) && $is_custom ) {
 444                      $template_files[ $template_slug ] = $candidate;
 445                  }
 446              }
 447          }
 448      }
 449  
 450      return array_values( $template_files );
 451  }
 452  
 453  /**
 454   * Attempts to add custom template information to the template item.
 455   *
 456   * @since 5.9.0
 457   * @access private
 458   *
 459   * @param array $template_item Template to add information to (requires 'slug' field).
 460   * @return array Template item.
 461   */
 462  function _add_block_template_info( $template_item ) {
 463      if ( ! wp_theme_has_theme_json() ) {
 464          return $template_item;
 465      }
 466  
 467      $theme_data = wp_get_theme_data_custom_templates();
 468      if ( isset( $theme_data[ $template_item['slug'] ] ) ) {
 469          $template_item['title']     = $theme_data[ $template_item['slug'] ]['title'];
 470          $template_item['postTypes'] = $theme_data[ $template_item['slug'] ]['postTypes'];
 471      }
 472  
 473      return $template_item;
 474  }
 475  
 476  /**
 477   * Attempts to add the template part's area information to the input template.
 478   *
 479   * @since 5.9.0
 480   * @access private
 481   *
 482   * @param array $template_info Template to add information to (requires 'type' and 'slug' fields).
 483   * @return array Template info.
 484   */
 485  function _add_block_template_part_area_info( $template_info ) {
 486      if ( wp_theme_has_theme_json() ) {
 487          $theme_data = wp_get_theme_data_template_parts();
 488      }
 489  
 490      if ( isset( $theme_data[ $template_info['slug'] ]['area'] ) ) {
 491          $template_info['title'] = $theme_data[ $template_info['slug'] ]['title'];
 492          $template_info['area']  = _filter_block_template_part_area( $theme_data[ $template_info['slug'] ]['area'] );
 493      } else {
 494          $template_info['area'] = WP_TEMPLATE_PART_AREA_UNCATEGORIZED;
 495      }
 496  
 497      return $template_info;
 498  }
 499  
 500  /**
 501   * Returns an array containing the references of
 502   * the passed blocks and their inner blocks.
 503   *
 504   * @since 5.9.0
 505   * @access private
 506   *
 507   * @param array $blocks array of blocks.
 508   * @return array block references to the passed blocks and their inner blocks.
 509   */
 510  function _flatten_blocks( &$blocks ) {
 511      $all_blocks = array();
 512      $queue      = array();
 513      foreach ( $blocks as &$block ) {
 514          $queue[] = &$block;
 515      }
 516  
 517      while ( count( $queue ) > 0 ) {
 518          $block = &$queue[0];
 519          array_shift( $queue );
 520          $all_blocks[] = &$block;
 521  
 522          if ( ! empty( $block['innerBlocks'] ) ) {
 523              foreach ( $block['innerBlocks'] as &$inner_block ) {
 524                  $queue[] = &$inner_block;
 525              }
 526          }
 527      }
 528  
 529      return $all_blocks;
 530  }
 531  
 532  /**
 533   * Injects the active theme's stylesheet as a `theme` attribute
 534   * into a given template part block.
 535   *
 536   * @since 6.4.0
 537   * @access private
 538   *
 539   * @param array $block a parsed block.
 540   */
 541  function _inject_theme_attribute_in_template_part_block( &$block ) {
 542      if (
 543          'core/template-part' === $block['blockName'] &&
 544          ! isset( $block['attrs']['theme'] )
 545      ) {
 546          $block['attrs']['theme'] = get_stylesheet();
 547      }
 548  }
 549  
 550  /**
 551   * Removes the `theme` attribute from a given template part block.
 552   *
 553   * @since 6.4.0
 554   * @access private
 555   *
 556   * @param array $block a parsed block.
 557   */
 558  function _remove_theme_attribute_from_template_part_block( &$block ) {
 559      if (
 560          'core/template-part' === $block['blockName'] &&
 561          isset( $block['attrs']['theme'] )
 562      ) {
 563          unset( $block['attrs']['theme'] );
 564      }
 565  }
 566  
 567  /**
 568   * Builds a unified template object based on a theme file.
 569   *
 570   * @since 5.9.0
 571   * @since 6.3.0 Added `modified` property to template objects.
 572   * @access private
 573   *
 574   * @param array  $template_file Theme file.
 575   * @param string $template_type Template type. Either 'wp_template' or 'wp_template_part'.
 576   * @return WP_Block_Template Template.
 577   */
 578  function _build_block_template_result_from_file( $template_file, $template_type ) {
 579      $default_template_types = get_default_block_template_types();
 580      $theme                  = get_stylesheet();
 581  
 582      $template                 = new WP_Block_Template();
 583      $template->id             = $theme . '//' . $template_file['slug'];
 584      $template->theme          = $theme;
 585      $template->content        = file_get_contents( $template_file['path'] );
 586      $template->slug           = $template_file['slug'];
 587      $template->source         = 'theme';
 588      $template->type           = $template_type;
 589      $template->title          = ! empty( $template_file['title'] ) ? $template_file['title'] : $template_file['slug'];
 590      $template->status         = 'publish';
 591      $template->has_theme_file = true;
 592      $template->is_custom      = true;
 593      $template->modified       = null;
 594  
 595      if ( 'wp_template' === $template_type ) {
 596          $registered_template = WP_Block_Templates_Registry::get_instance()->get_by_slug( $template_file['slug'] );
 597          if ( $registered_template ) {
 598              $template->plugin      = $registered_template->plugin;
 599              $template->title       = empty( $template->title ) || $template->title === $template->slug ? $registered_template->title : $template->title;
 600              $template->description = empty( $template->description ) ? $registered_template->description : $template->description;
 601          }
 602      }
 603  
 604      if ( 'wp_template' === $template_type && isset( $default_template_types[ $template_file['slug'] ] ) ) {
 605          $template->description = $default_template_types[ $template_file['slug'] ]['description'];
 606          $template->title       = $default_template_types[ $template_file['slug'] ]['title'];
 607          $template->is_custom   = false;
 608      }
 609  
 610      if ( 'wp_template' === $template_type && isset( $template_file['postTypes'] ) ) {
 611          $template->post_types = $template_file['postTypes'];
 612      }
 613  
 614      if ( 'wp_template_part' === $template_type && isset( $template_file['area'] ) ) {
 615          $template->area = $template_file['area'];
 616      }
 617  
 618      if ( 'wp_template_part' === $template->type ) {
 619          /*
 620           * In order for hooked blocks to be inserted at positions first_child and last_child in a template part,
 621           * we need to wrap its content a mock template part block and traverse it.
 622           */
 623          $content           = get_comment_delimited_block_content(
 624              'core/template-part',
 625              array(),
 626              $template->content
 627          );
 628          $content           = apply_block_hooks_to_content(
 629              $content,
 630              $template,
 631              'insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata'
 632          );
 633          $template->content = remove_serialized_parent_block( $content );
 634      } else {
 635          $template->content = apply_block_hooks_to_content(
 636              $template->content,
 637              $template,
 638              'insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata'
 639          );
 640      }
 641  
 642      return $template;
 643  }
 644  
 645  /**
 646   * Builds the title and description of a post-specific template based on the underlying referenced post.
 647   *
 648   * Mutates the underlying template object.
 649   *
 650   * @since 6.1.0
 651   * @access private
 652   *
 653   * @param string            $post_type Post type, e.g. page, post, product.
 654   * @param string            $slug      Slug of the post, e.g. a-story-about-shoes.
 655   * @param WP_Block_Template $template  Template to mutate adding the description and title computed.
 656   * @return bool Returns true if the referenced post was found and false otherwise.
 657   */
 658  function _wp_build_title_and_description_for_single_post_type_block_template( $post_type, $slug, WP_Block_Template $template ) {
 659      $post_type_object = get_post_type_object( $post_type );
 660  
 661      $default_args = array(
 662          'post_type'              => $post_type,
 663          'post_status'            => 'publish',
 664          'posts_per_page'         => 1,
 665          'update_post_meta_cache' => false,
 666          'update_post_term_cache' => false,
 667          'ignore_sticky_posts'    => true,
 668          'no_found_rows'          => true,
 669      );
 670  
 671      $args = array(
 672          'name' => $slug,
 673      );
 674      $args = wp_parse_args( $args, $default_args );
 675  
 676      $posts_query = new WP_Query( $args );
 677  
 678      if ( empty( $posts_query->posts ) ) {
 679          $template->title = sprintf(
 680              /* translators: Custom template title in the Site Editor referencing a post that was not found. 1: Post type singular name, 2: Post type slug. */
 681              __( 'Not found: %1$s (%2$s)' ),
 682              $post_type_object->labels->singular_name,
 683              $slug
 684          );
 685  
 686          return false;
 687      }
 688  
 689      $post_title = $posts_query->posts[0]->post_title;
 690  
 691      $template->title = sprintf(
 692          /* translators: Custom template title in the Site Editor. 1: Post type singular name, 2: Post title. */
 693          __( '%1$s: %2$s' ),
 694          $post_type_object->labels->singular_name,
 695          $post_title
 696      );
 697  
 698      $template->description = sprintf(
 699          /* translators: Custom template description in the Site Editor. %s: Post title. */
 700          __( 'Template for %s' ),
 701          $post_title
 702      );
 703  
 704      $args = array(
 705          'title' => $post_title,
 706      );
 707      $args = wp_parse_args( $args, $default_args );
 708  
 709      $posts_with_same_title_query = new WP_Query( $args );
 710  
 711      if ( count( $posts_with_same_title_query->posts ) > 1 ) {
 712          $template->title = sprintf(
 713              /* translators: Custom template title in the Site Editor. 1: Template title, 2: Post type slug. */
 714              __( '%1$s (%2$s)' ),
 715              $template->title,
 716              $slug
 717          );
 718      }
 719  
 720      return true;
 721  }
 722  
 723  /**
 724   * Builds the title and description of a taxonomy-specific template based on the underlying entity referenced.
 725   *
 726   * Mutates the underlying template object.
 727   *
 728   * @since 6.1.0
 729   * @access private
 730   *
 731   * @param string            $taxonomy Identifier of the taxonomy, e.g. category.
 732   * @param string            $slug     Slug of the term, e.g. shoes.
 733   * @param WP_Block_Template $template Template to mutate adding the description and title computed.
 734   * @return bool True if the term referenced was found and false otherwise.
 735   */
 736  function _wp_build_title_and_description_for_taxonomy_block_template( $taxonomy, $slug, WP_Block_Template $template ) {
 737      $taxonomy_object = get_taxonomy( $taxonomy );
 738  
 739      $default_args = array(
 740          'taxonomy'               => $taxonomy,
 741          'hide_empty'             => false,
 742          'update_term_meta_cache' => false,
 743      );
 744  
 745      $term_query = new WP_Term_Query();
 746  
 747      $args = array(
 748          'number' => 1,
 749          'slug'   => $slug,
 750      );
 751      $args = wp_parse_args( $args, $default_args );
 752  
 753      $terms_query = $term_query->query( $args );
 754  
 755      if ( empty( $terms_query ) ) {
 756          $template->title = sprintf(
 757              /* translators: Custom template title in the Site Editor, referencing a taxonomy term that was not found. 1: Taxonomy singular name, 2: Term slug. */
 758              __( 'Not found: %1$s (%2$s)' ),
 759              $taxonomy_object->labels->singular_name,
 760              $slug
 761          );
 762          return false;
 763      }
 764  
 765      $term_title = $terms_query[0]->name;
 766  
 767      $template->title = sprintf(
 768          /* translators: Custom template title in the Site Editor. 1: Taxonomy singular name, 2: Term title. */
 769          __( '%1$s: %2$s' ),
 770          $taxonomy_object->labels->singular_name,
 771          $term_title
 772      );
 773  
 774      $template->description = sprintf(
 775          /* translators: Custom template description in the Site Editor. %s: Term title. */
 776          __( 'Template for %s' ),
 777          $term_title
 778      );
 779  
 780      $term_query = new WP_Term_Query();
 781  
 782      $args = array(
 783          'number' => 2,
 784          'name'   => $term_title,
 785      );
 786      $args = wp_parse_args( $args, $default_args );
 787  
 788      $terms_with_same_title_query = $term_query->query( $args );
 789  
 790      if ( count( $terms_with_same_title_query ) > 1 ) {
 791          $template->title = sprintf(
 792              /* translators: Custom template title in the Site Editor. 1: Template title, 2: Term slug. */
 793              __( '%1$s (%2$s)' ),
 794              $template->title,
 795              $slug
 796          );
 797      }
 798  
 799      return true;
 800  }
 801  
 802  /**
 803   * Builds a block template object from a post object.
 804   *
 805   * This is a helper function that creates a block template object from a given post object.
 806   * It is self-sufficient in that it only uses information passed as arguments; it does not
 807   * query the database for additional information.
 808   *
 809   * @since 6.5.3
 810   * @access private
 811   *
 812   * @param WP_Post $post  Template post.
 813   * @param array   $terms Additional terms to inform the template object.
 814   * @param array   $meta  Additional meta fields to inform the template object.
 815   * @return WP_Block_Template|WP_Error Template or error object.
 816   */
 817  function _build_block_template_object_from_post_object( $post, $terms = array(), $meta = array() ) {
 818      if ( empty( $terms['wp_theme'] ) ) {
 819          return new WP_Error( 'template_missing_theme', __( 'No theme is defined for this template.' ) );
 820      }
 821      $theme = $terms['wp_theme'];
 822  
 823      $default_template_types = get_default_block_template_types();
 824  
 825      $template_file  = _get_block_template_file( $post->post_type, $post->post_name );
 826      $has_theme_file = get_stylesheet() === $theme && null !== $template_file;
 827  
 828      $template                 = new WP_Block_Template();
 829      $template->wp_id          = $post->ID;
 830      $template->id             = $theme . '//' . $post->post_name;
 831      $template->theme          = $theme;
 832      $template->content        = $post->post_content;
 833      $template->slug           = $post->post_name;
 834      $template->source         = 'custom';
 835      $template->origin         = ! empty( $meta['origin'] ) ? $meta['origin'] : null;
 836      $template->type           = $post->post_type;
 837      $template->description    = $post->post_excerpt;
 838      $template->title          = $post->post_title;
 839      $template->status         = $post->post_status;
 840      $template->has_theme_file = $has_theme_file;
 841      $template->is_custom      = empty( $meta['is_wp_suggestion'] );
 842      $template->author         = $post->post_author;
 843      $template->modified       = $post->post_modified;
 844  
 845      if ( 'wp_template' === $post->post_type && $has_theme_file && isset( $template_file['postTypes'] ) ) {
 846          $template->post_types = $template_file['postTypes'];
 847      }
 848  
 849      if ( 'wp_template' === $post->post_type && isset( $default_template_types[ $template->slug ] ) ) {
 850          $template->is_custom = false;
 851      }
 852  
 853      if ( 'wp_template_part' === $post->post_type && isset( $terms['wp_template_part_area'] ) ) {
 854          $template->area = $terms['wp_template_part_area'];
 855      }
 856  
 857      return $template;
 858  }
 859  
 860  /**
 861   * Builds a unified template object based a post Object.
 862   *
 863   * @since 5.9.0
 864   * @since 6.3.0 Added `modified` property to template objects.
 865   * @since 6.4.0 Added support for a revision post to be passed to this function.
 866   * @access private
 867   *
 868   * @param WP_Post $post Template post.
 869   * @return WP_Block_Template|WP_Error Template or error object.
 870   */
 871  function _build_block_template_result_from_post( $post ) {
 872      $post_id = wp_is_post_revision( $post );
 873      if ( ! $post_id ) {
 874          $post_id = $post;
 875      }
 876      $parent_post     = get_post( $post_id );
 877      $post->post_name = $parent_post->post_name;
 878      $post->post_type = $parent_post->post_type;
 879  
 880      $terms = get_the_terms( $parent_post, 'wp_theme' );
 881  
 882      if ( is_wp_error( $terms ) ) {
 883          return $terms;
 884      }
 885  
 886      if ( ! $terms ) {
 887          return new WP_Error( 'template_missing_theme', __( 'No theme is defined for this template.' ) );
 888      }
 889  
 890      $terms = array(
 891          'wp_theme' => $terms[0]->name,
 892      );
 893  
 894      if ( 'wp_template_part' === $parent_post->post_type ) {
 895          $type_terms = get_the_terms( $parent_post, 'wp_template_part_area' );
 896          if ( ! is_wp_error( $type_terms ) && false !== $type_terms ) {
 897              $terms['wp_template_part_area'] = $type_terms[0]->name;
 898          }
 899      }
 900  
 901      $meta = array(
 902          'origin'           => get_post_meta( $parent_post->ID, 'origin', true ),
 903          'is_wp_suggestion' => get_post_meta( $parent_post->ID, 'is_wp_suggestion', true ),
 904      );
 905  
 906      $template = _build_block_template_object_from_post_object( $post, $terms, $meta );
 907  
 908      if ( is_wp_error( $template ) ) {
 909          return $template;
 910      }
 911  
 912      // Check for a block template without a description and title or with a title equal to the slug.
 913      if ( 'wp_template' === $parent_post->post_type && empty( $template->description ) && ( empty( $template->title ) || $template->title === $template->slug ) ) {
 914          $matches = array();
 915  
 916          // Check for a block template for a single author, page, post, tag, category, custom post type, or custom taxonomy.
 917          if ( preg_match( '/(author|page|single|tag|category|taxonomy)-(.+)/', $template->slug, $matches ) ) {
 918              $type           = $matches[1];
 919              $slug_remaining = $matches[2];
 920  
 921              switch ( $type ) {
 922                  case 'author':
 923                      $nice_name = $slug_remaining;
 924                      $users     = get_users(
 925                          array(
 926                              'capability'     => 'edit_posts',
 927                              'search'         => $nice_name,
 928                              'search_columns' => array( 'user_nicename' ),
 929                              'fields'         => 'display_name',
 930                          )
 931                      );
 932  
 933                      if ( empty( $users ) ) {
 934                          $template->title = sprintf(
 935                              /* translators: Custom template title in the Site Editor, referencing a deleted author. %s: Author nicename. */
 936                              __( 'Deleted author: %s' ),
 937                              $nice_name
 938                          );
 939                      } else {
 940                          $author_name = $users[0];
 941  
 942                          $template->title = sprintf(
 943                              /* translators: Custom template title in the Site Editor. %s: Author name. */
 944                              __( 'Author: %s' ),
 945                              $author_name
 946                          );
 947  
 948                          $template->description = sprintf(
 949                              /* translators: Custom template description in the Site Editor. %s: Author name. */
 950                              __( 'Template for %s' ),
 951                              $author_name
 952                          );
 953  
 954                          $users_with_same_name = get_users(
 955                              array(
 956                                  'capability'     => 'edit_posts',
 957                                  'search'         => $author_name,
 958                                  'search_columns' => array( 'display_name' ),
 959                                  'fields'         => 'display_name',
 960                              )
 961                          );
 962  
 963                          if ( count( $users_with_same_name ) > 1 ) {
 964                              $template->title = sprintf(
 965                                  /* translators: Custom template title in the Site Editor. 1: Template title of an author template, 2: Author nicename. */
 966                                  __( '%1$s (%2$s)' ),
 967                                  $template->title,
 968                                  $nice_name
 969                              );
 970                          }
 971                      }
 972                      break;
 973                  case 'page':
 974                      _wp_build_title_and_description_for_single_post_type_block_template( 'page', $slug_remaining, $template );
 975                      break;
 976                  case 'single':
 977                      $post_types = get_post_types();
 978  
 979                      foreach ( $post_types as $post_type ) {
 980                          $post_type_length = strlen( $post_type ) + 1;
 981  
 982                          // If $slug_remaining starts with $post_type followed by a hyphen.
 983                          if ( 0 === strncmp( $slug_remaining, $post_type . '-', $post_type_length ) ) {
 984                              $slug  = substr( $slug_remaining, $post_type_length, strlen( $slug_remaining ) );
 985                              $found = _wp_build_title_and_description_for_single_post_type_block_template( $post_type, $slug, $template );
 986  
 987                              if ( $found ) {
 988                                  break;
 989                              }
 990                          }
 991                      }
 992                      break;
 993                  case 'tag':
 994                      _wp_build_title_and_description_for_taxonomy_block_template( 'post_tag', $slug_remaining, $template );
 995                      break;
 996                  case 'category':
 997                      _wp_build_title_and_description_for_taxonomy_block_template( 'category', $slug_remaining, $template );
 998                      break;
 999                  case 'taxonomy':
1000                      $taxonomies = get_taxonomies();
1001  
1002                      foreach ( $taxonomies as $taxonomy ) {
1003                          $taxonomy_length = strlen( $taxonomy ) + 1;
1004  
1005                          // If $slug_remaining starts with $taxonomy followed by a hyphen.
1006                          if ( 0 === strncmp( $slug_remaining, $taxonomy . '-', $taxonomy_length ) ) {
1007                              $slug  = substr( $slug_remaining, $taxonomy_length, strlen( $slug_remaining ) );
1008                              $found = _wp_build_title_and_description_for_taxonomy_block_template( $taxonomy, $slug, $template );
1009  
1010                              if ( $found ) {
1011                                  break;
1012                              }
1013                          }
1014                      }
1015                      break;
1016              }
1017          }
1018      }
1019  
1020      if ( 'wp_template' === $post->post_type ) {
1021          $registered_template = WP_Block_Templates_Registry::get_instance()->get_by_slug( $template->slug );
1022          if ( $registered_template ) {
1023              $template->plugin      = $registered_template->plugin;
1024              $template->origin      =
1025                  'theme' !== $template->origin && 'theme' !== $template->source ?
1026                  'plugin' :
1027                  $template->origin;
1028              $template->title       = empty( $template->title ) || $template->title === $template->slug ? $registered_template->title : $template->title;
1029              $template->description = empty( $template->description ) ? $registered_template->description : $template->description;
1030          }
1031      }
1032  
1033      if ( 'wp_template_part' === $template->type ) {
1034          $existing_ignored_hooked_blocks = get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true );
1035          $attributes                     = ! empty( $existing_ignored_hooked_blocks ) ? array( 'metadata' => array( 'ignoredHookedBlocks' => json_decode( $existing_ignored_hooked_blocks, true ) ) ) : array();
1036  
1037          /*
1038           * In order for hooked blocks to be inserted at positions first_child and last_child in a template part,
1039           * we need to wrap its content a mock template part block and traverse it.
1040           */
1041          $content           = get_comment_delimited_block_content(
1042              'core/template-part',
1043              $attributes,
1044              $template->content
1045          );
1046          $content           = apply_block_hooks_to_content(
1047              $content,
1048              $template,
1049              'insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata'
1050          );
1051          $template->content = remove_serialized_parent_block( $content );
1052      } else {
1053          $template->content = apply_block_hooks_to_content(
1054              $template->content,
1055              $template,
1056              'insert_hooked_blocks_and_set_ignored_hooked_blocks_metadata'
1057          );
1058      }
1059  
1060      return $template;
1061  }
1062  
1063  /**
1064   * Retrieves a list of unified template objects based on a query.
1065   *
1066   * @since 5.8.0
1067   *
1068   * @param array  $query {
1069   *     Optional. Arguments to retrieve templates.
1070   *
1071   *     @type string[] $slug__in  List of slugs to include.
1072   *     @type int      $wp_id     Post ID of customized template.
1073   *     @type string   $area      A 'wp_template_part_area' taxonomy value to filter by (for 'wp_template_part' template type only).
1074   *     @type string   $post_type Post type to get the templates for.
1075   * }
1076   * @param string $template_type Template type. Either 'wp_template' or 'wp_template_part'.
1077   * @return WP_Block_Template[] Array of block templates.
1078   */
1079  function get_block_templates( $query = array(), $template_type = 'wp_template' ) {
1080      /**
1081       * Filters the block templates array before the query takes place.
1082       *
1083       * Return a non-null value to bypass the WordPress queries.
1084       *
1085       * @since 5.9.0
1086       *
1087       * @param WP_Block_Template[]|null $block_templates Return an array of block templates to short-circuit the default query,
1088       *                                                  or null to allow WP to run its normal queries.
1089       * @param array  $query {
1090       *     Arguments to retrieve templates. All arguments are optional.
1091       *
1092       *     @type string[] $slug__in  List of slugs to include.
1093       *     @type int      $wp_id     Post ID of customized template.
1094       *     @type string   $area      A 'wp_template_part_area' taxonomy value to filter by (for 'wp_template_part' template type only).
1095       *     @type string   $post_type Post type to get the templates for.
1096       * }
1097       * @param string $template_type Template type. Either 'wp_template' or 'wp_template_part'.
1098       */
1099      $templates = apply_filters( 'pre_get_block_templates', null, $query, $template_type );
1100      if ( ! is_null( $templates ) ) {
1101          return $templates;
1102      }
1103  
1104      $post_type     = isset( $query['post_type'] ) ? $query['post_type'] : '';
1105      $wp_query_args = array(
1106          'post_status'         => array( 'auto-draft', 'draft', 'publish' ),
1107          'post_type'           => $template_type,
1108          'posts_per_page'      => -1,
1109          'no_found_rows'       => true,
1110          'lazy_load_term_meta' => false,
1111          'tax_query'           => array(
1112              array(
1113                  'taxonomy' => 'wp_theme',
1114                  'field'    => 'name',
1115                  'terms'    => get_stylesheet(),
1116              ),
1117          ),
1118      );
1119  
1120      if ( 'wp_template_part' === $template_type && isset( $query['area'] ) ) {
1121          $wp_query_args['tax_query'][]           = array(
1122              'taxonomy' => 'wp_template_part_area',
1123              'field'    => 'name',
1124              'terms'    => $query['area'],
1125          );
1126          $wp_query_args['tax_query']['relation'] = 'AND';
1127      }
1128  
1129      if ( ! empty( $query['slug__in'] ) ) {
1130          $wp_query_args['post_name__in']  = $query['slug__in'];
1131          $wp_query_args['posts_per_page'] = count( array_unique( $query['slug__in'] ) );
1132      }
1133  
1134      // This is only needed for the regular templates/template parts post type listing and editor.
1135      if ( isset( $query['wp_id'] ) ) {
1136          $wp_query_args['p'] = $query['wp_id'];
1137      } else {
1138          $wp_query_args['post_status'] = 'publish';
1139      }
1140  
1141      $template_query = new WP_Query( $wp_query_args );
1142      $query_result   = array();
1143      foreach ( $template_query->posts as $post ) {
1144          $template = _build_block_template_result_from_post( $post );
1145  
1146          if ( is_wp_error( $template ) ) {
1147              continue;
1148          }
1149  
1150          if ( $post_type && ! $template->is_custom ) {
1151              continue;
1152          }
1153  
1154          if (
1155              $post_type &&
1156              isset( $template->post_types ) &&
1157              ! in_array( $post_type, $template->post_types, true )
1158          ) {
1159              continue;
1160          }
1161  
1162          $query_result[] = $template;
1163      }
1164  
1165      if ( ! isset( $query['wp_id'] ) ) {
1166          /*
1167           * If the query has found some user templates, those have priority
1168           * over the theme-provided ones, so we skip querying and building them.
1169           */
1170          $query['slug__not_in'] = wp_list_pluck( $query_result, 'slug' );
1171          $template_files        = _get_block_templates_files( $template_type, $query );
1172          foreach ( $template_files as $template_file ) {
1173              $query_result[] = _build_block_template_result_from_file( $template_file, $template_type );
1174          }
1175  
1176          if ( 'wp_template' === $template_type ) {
1177              // Add templates registered in the template registry. Filtering out the ones which have a theme file.
1178              $registered_templates          = WP_Block_Templates_Registry::get_instance()->get_by_query( $query );
1179              $matching_registered_templates = array_filter(
1180                  $registered_templates,
1181                  function ( $registered_template ) use ( $template_files ) {
1182                      foreach ( $template_files as $template_file ) {
1183                          if ( $template_file['slug'] === $registered_template->slug ) {
1184                              return false;
1185                          }
1186                      }
1187                      return true;
1188                  }
1189              );
1190              $query_result                  = array_merge( $query_result, $matching_registered_templates );
1191          }
1192      }
1193  
1194      /**
1195       * Filters the array of queried block templates array after they've been fetched.
1196       *
1197       * @since 5.9.0
1198       *
1199       * @param WP_Block_Template[] $query_result Array of found block templates.
1200       * @param array               $query {
1201       *     Arguments to retrieve templates. All arguments are optional.
1202       *
1203       *     @type string[] $slug__in  List of slugs to include.
1204       *     @type int      $wp_id     Post ID of customized template.
1205       *     @type string   $area      A 'wp_template_part_area' taxonomy value to filter by (for 'wp_template_part' template type only).
1206       *     @type string   $post_type Post type to get the templates for.
1207       * }
1208       * @param string              $template_type wp_template or wp_template_part.
1209       */
1210      return apply_filters( 'get_block_templates', $query_result, $query, $template_type );
1211  }
1212  
1213  /**
1214   * Retrieves a single unified template object using its id.
1215   *
1216   * @since 5.8.0
1217   *
1218   * @param string $id            Template unique identifier (example: 'theme_slug//template_slug').
1219   * @param string $template_type Optional. Template type. Either 'wp_template' or 'wp_template_part'.
1220   *                              Default 'wp_template'.
1221   * @return WP_Block_Template|null Template.
1222   */
1223  function get_block_template( $id, $template_type = 'wp_template' ) {
1224      /**
1225       * Filters the block template object before the query takes place.
1226       *
1227       * Return a non-null value to bypass the WordPress queries.
1228       *
1229       * @since 5.9.0
1230       *
1231       * @param WP_Block_Template|null $block_template Return block template object to short-circuit the default query,
1232       *                                               or null to allow WP to run its normal queries.
1233       * @param string                 $id             Template unique identifier (example: 'theme_slug//template_slug').
1234       * @param string                 $template_type  Template type. Either 'wp_template' or 'wp_template_part'.
1235       */
1236      $block_template = apply_filters( 'pre_get_block_template', null, $id, $template_type );
1237      if ( ! is_null( $block_template ) ) {
1238          return $block_template;
1239      }
1240  
1241      $parts = explode( '//', $id, 2 );
1242      if ( count( $parts ) < 2 ) {
1243          return null;
1244      }
1245      list( $theme, $slug ) = $parts;
1246      $wp_query_args        = array(
1247          'post_name__in'  => array( $slug ),
1248          'post_type'      => $template_type,
1249          'post_status'    => array( 'auto-draft', 'draft', 'publish', 'trash' ),
1250          'posts_per_page' => 1,
1251          'no_found_rows'  => true,
1252          'tax_query'      => array(
1253              array(
1254                  'taxonomy' => 'wp_theme',
1255                  'field'    => 'name',
1256                  'terms'    => $theme,
1257              ),
1258          ),
1259      );
1260      $template_query       = new WP_Query( $wp_query_args );
1261      $posts                = $template_query->posts;
1262  
1263      if ( count( $posts ) > 0 ) {
1264          $template = _build_block_template_result_from_post( $posts[0] );
1265  
1266          if ( ! is_wp_error( $template ) ) {
1267              return $template;
1268          }
1269      }
1270  
1271      $block_template = get_block_file_template( $id, $template_type );
1272  
1273      /**
1274       * Filters the queried block template object after it's been fetched.
1275       *
1276       * @since 5.9.0
1277       *
1278       * @param WP_Block_Template|null $block_template The found block template, or null if there isn't one.
1279       * @param string                 $id             Template unique identifier (example: 'theme_slug//template_slug').
1280       * @param string                 $template_type  Template type. Either 'wp_template' or 'wp_template_part'.
1281       */
1282      return apply_filters( 'get_block_template', $block_template, $id, $template_type );
1283  }
1284  
1285  /**
1286   * Retrieves a unified template object based on a theme file.
1287   *
1288   * This is a fallback of get_block_template(), used when no templates are found in the database.
1289   *
1290   * @since 5.9.0
1291   *
1292   * @param string $id            Template unique identifier (example: 'theme_slug//template_slug').
1293   * @param string $template_type Optional. Template type. Either 'wp_template' or 'wp_template_part'.
1294   *                              Default 'wp_template'.
1295   * @return WP_Block_Template|null The found block template, or null if there isn't one.
1296   */
1297  function get_block_file_template( $id, $template_type = 'wp_template' ) {
1298      /**
1299       * Filters the block template object before the theme file discovery takes place.
1300       *
1301       * Return a non-null value to bypass the WordPress theme file discovery.
1302       *
1303       * @since 5.9.0
1304       *
1305       * @param WP_Block_Template|null $block_template Return block template object to short-circuit the default query,
1306       *                                               or null to allow WP to run its normal queries.
1307       * @param string                 $id             Template unique identifier (example: 'theme_slug//template_slug').
1308       * @param string                 $template_type  Template type. Either 'wp_template' or 'wp_template_part'.
1309       */
1310      $block_template = apply_filters( 'pre_get_block_file_template', null, $id, $template_type );
1311      if ( ! is_null( $block_template ) ) {
1312          return $block_template;
1313      }
1314  
1315      $parts = explode( '//', $id, 2 );
1316      if ( count( $parts ) < 2 ) {
1317          /** This filter is documented in wp-includes/block-template-utils.php */
1318          return apply_filters( 'get_block_file_template', null, $id, $template_type );
1319      }
1320      list( $theme, $slug ) = $parts;
1321  
1322      if ( get_stylesheet() === $theme ) {
1323          $template_file = _get_block_template_file( $template_type, $slug );
1324          if ( null !== $template_file ) {
1325              $block_template = _build_block_template_result_from_file( $template_file, $template_type );
1326  
1327              /** This filter is documented in wp-includes/block-template-utils.php */
1328              return apply_filters( 'get_block_file_template', $block_template, $id, $template_type );
1329          }
1330      }
1331  
1332      $block_template = WP_Block_Templates_Registry::get_instance()->get_by_slug( $slug );
1333  
1334      /**
1335       * Filters the block template object after it has been (potentially) fetched from the theme file.
1336       *
1337       * @since 5.9.0
1338       *
1339       * @param WP_Block_Template|null $block_template The found block template, or null if there is none.
1340       * @param string                 $id             Template unique identifier (example: 'theme_slug//template_slug').
1341       * @param string                 $template_type  Template type. Either 'wp_template' or 'wp_template_part'.
1342       */
1343      return apply_filters( 'get_block_file_template', $block_template, $id, $template_type );
1344  }
1345  
1346  /**
1347   * Prints a block template part.
1348   *
1349   * @since 5.9.0
1350   *
1351   * @param string $part The block template part to print, for example 'header' or 'footer'.
1352   */
1353  function block_template_part( $part ) {
1354      $template_part = get_block_template( get_stylesheet() . '//' . $part, 'wp_template_part' );
1355      if ( ! $template_part || empty( $template_part->content ) ) {
1356          return;
1357      }
1358      echo do_blocks( $template_part->content );
1359  }
1360  
1361  /**
1362   * Prints the header block template part.
1363   *
1364   * @since 5.9.0
1365   */
1366  function block_header_area() {
1367      block_template_part( 'header' );
1368  }
1369  
1370  /**
1371   * Prints the footer block template part.
1372   *
1373   * @since 5.9.0
1374   */
1375  function block_footer_area() {
1376      block_template_part( 'footer' );
1377  }
1378  
1379  /**
1380   * Determines whether a theme directory should be ignored during export.
1381   *
1382   * @since 6.0.0
1383   *
1384   * @param string $path The path of the file in the theme.
1385   * @return bool Whether this file is in an ignored directory.
1386   */
1387  function wp_is_theme_directory_ignored( $path ) {
1388      $directories_to_ignore = array( '.DS_Store', '.svn', '.git', '.hg', '.bzr', 'node_modules', 'vendor' );
1389  
1390      foreach ( $directories_to_ignore as $directory ) {
1391          if ( str_starts_with( $path, $directory ) ) {
1392              return true;
1393          }
1394      }
1395  
1396      return false;
1397  }
1398  
1399  /**
1400   * Creates an export of the current templates and
1401   * template parts from the site editor at the
1402   * specified path in a ZIP file.
1403   *
1404   * @since 5.9.0
1405   * @since 6.0.0 Adds the whole theme to the export archive.
1406   *
1407   * @return WP_Error|string Path of the ZIP file or error on failure.
1408   */
1409  function wp_generate_block_templates_export_file() {
1410      $wp_version = wp_get_wp_version();
1411  
1412      if ( ! class_exists( 'ZipArchive' ) ) {
1413          return new WP_Error( 'missing_zip_package', __( 'Zip Export not supported.' ) );
1414      }
1415  
1416      $obscura    = wp_generate_password( 12, false, false );
1417      $theme_name = basename( get_stylesheet() );
1418      $filename   = get_temp_dir() . $theme_name . $obscura . '.zip';
1419  
1420      $zip = new ZipArchive();
1421      if ( true !== $zip->open( $filename, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
1422          return new WP_Error( 'unable_to_create_zip', __( 'Unable to open export file (archive) for writing.' ) );
1423      }
1424  
1425      $zip->addEmptyDir( 'templates' );
1426      $zip->addEmptyDir( 'parts' );
1427  
1428      // Get path of the theme.
1429      $theme_path = wp_normalize_path( get_stylesheet_directory() );
1430  
1431      // Create recursive directory iterator.
1432      $theme_files = new RecursiveIteratorIterator(
1433          new RecursiveDirectoryIterator( $theme_path ),
1434          RecursiveIteratorIterator::LEAVES_ONLY
1435      );
1436  
1437      // Make a copy of the current theme.
1438      foreach ( $theme_files as $file ) {
1439          // Skip directories as they are added automatically.
1440          if ( ! $file->isDir() ) {
1441              // Get real and relative path for current file.
1442              $file_path     = wp_normalize_path( $file );
1443              $relative_path = substr( $file_path, strlen( $theme_path ) + 1 );
1444  
1445              if ( ! wp_is_theme_directory_ignored( $relative_path ) ) {
1446                  $zip->addFile( $file_path, $relative_path );
1447              }
1448          }
1449      }
1450  
1451      // Load templates into the zip file.
1452      $templates = get_block_templates();
1453      foreach ( $templates as $template ) {
1454          $template->content = traverse_and_serialize_blocks(
1455              parse_blocks( $template->content ),
1456              '_remove_theme_attribute_from_template_part_block'
1457          );
1458  
1459          $zip->addFromString(
1460              'templates/' . $template->slug . '.html',
1461              $template->content
1462          );
1463      }
1464  
1465      // Load template parts into the zip file.
1466      $template_parts = get_block_templates( array(), 'wp_template_part' );
1467      foreach ( $template_parts as $template_part ) {
1468          $zip->addFromString(
1469              'parts/' . $template_part->slug . '.html',
1470              $template_part->content
1471          );
1472      }
1473  
1474      // Load theme.json into the zip file.
1475      $tree = WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) );
1476      // Merge with user data.
1477      $tree->merge( WP_Theme_JSON_Resolver::get_user_data() );
1478  
1479      $theme_json_raw = $tree->get_data();
1480      // If a version is defined, add a schema.
1481      if ( $theme_json_raw['version'] ) {
1482          $theme_json_version = 'wp/' . substr( $wp_version, 0, 3 );
1483          $schema             = array( '$schema' => 'https://schemas.wp.org/' . $theme_json_version . '/theme.json' );
1484          $theme_json_raw     = array_merge( $schema, $theme_json_raw );
1485      }
1486  
1487      // Convert to a string.
1488      $theme_json_encoded = wp_json_encode( $theme_json_raw, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1489  
1490      // Replace 4 spaces with a tab.
1491      $theme_json_tabbed = preg_replace( '~(?:^|\G)\h{4}~m', "\t", $theme_json_encoded );
1492  
1493      // Add the theme.json file to the zip.
1494      $zip->addFromString(
1495          'theme.json',
1496          $theme_json_tabbed
1497      );
1498  
1499      // Save changes to the zip file.
1500      $zip->close();
1501  
1502      return $filename;
1503  }
1504  
1505  /**
1506   * Gets the template hierarchy for the given template slug to be created.
1507   *
1508   * Note: Always add `index` as the last fallback template.
1509   *
1510   * @since 6.1.0
1511   *
1512   * @param string $slug            The template slug to be created.
1513   * @param bool   $is_custom       Optional. Indicates if a template is custom or
1514   *                                part of the template hierarchy. Default false.
1515   * @param string $template_prefix Optional. The template prefix for the created template.
1516   *                                Used to extract the main template type, e.g.
1517   *                                in `taxonomy-books` the `taxonomy` is extracted.
1518   *                                Default empty string.
1519   * @return string[] The template hierarchy.
1520   */
1521  function get_template_hierarchy( $slug, $is_custom = false, $template_prefix = '' ) {
1522      if ( 'index' === $slug ) {
1523          /** This filter is documented in wp-includes/template.php */
1524          return apply_filters( 'index_template_hierarchy', array( 'index' ) );
1525      }
1526      if ( $is_custom ) {
1527          /** This filter is documented in wp-includes/template.php */
1528          return apply_filters( 'page_template_hierarchy', array( 'page', 'singular', 'index' ) );
1529      }
1530      if ( 'front-page' === $slug ) {
1531          /** This filter is documented in wp-includes/template.php */
1532          return apply_filters( 'frontpage_template_hierarchy', array( 'front-page', 'home', 'index' ) );
1533      }
1534  
1535      $matches = array();
1536  
1537      $template_hierarchy = array( $slug );
1538      // Most default templates don't have `$template_prefix` assigned.
1539      if ( ! empty( $template_prefix ) ) {
1540          list( $type ) = explode( '-', $template_prefix );
1541          // We need these checks because we always add the `$slug` above.
1542          if ( ! in_array( $template_prefix, array( $slug, $type ), true ) ) {
1543              $template_hierarchy[] = $template_prefix;
1544          }
1545          if ( $slug !== $type ) {
1546              $template_hierarchy[] = $type;
1547          }
1548      } elseif ( preg_match( '/^(author|category|archive|tag|page)-.+$/', $slug, $matches ) ) {
1549          $template_hierarchy[] = $matches[1];
1550      } elseif ( preg_match( '/^(taxonomy|single)-(.+)$/', $slug, $matches ) ) {
1551          $type           = $matches[1];
1552          $slug_remaining = $matches[2];
1553  
1554          $items = 'single' === $type ? get_post_types() : get_taxonomies();
1555          foreach ( $items as $item ) {
1556              if ( ! str_starts_with( $slug_remaining, $item ) ) {
1557                      continue;
1558              }
1559  
1560              // If $slug_remaining is equal to $post_type or $taxonomy we have
1561              // the single-$post_type template or the taxonomy-$taxonomy template.
1562              if ( $slug_remaining === $item ) {
1563                  $template_hierarchy[] = $type;
1564                  break;
1565              }
1566  
1567              // If $slug_remaining is single-$post_type-$slug template.
1568              if ( strlen( $slug_remaining ) > strlen( $item ) + 1 ) {
1569                  $template_hierarchy[] = "$type-$item";
1570                  $template_hierarchy[] = $type;
1571                  break;
1572              }
1573          }
1574      }
1575      // Handle `archive` template.
1576      if (
1577          str_starts_with( $slug, 'author' ) ||
1578          str_starts_with( $slug, 'taxonomy' ) ||
1579          str_starts_with( $slug, 'category' ) ||
1580          str_starts_with( $slug, 'tag' ) ||
1581          'date' === $slug
1582      ) {
1583          $template_hierarchy[] = 'archive';
1584      }
1585      // Handle `single` template.
1586      if ( 'attachment' === $slug ) {
1587          $template_hierarchy[] = 'single';
1588      }
1589      // Handle `singular` template.
1590      if (
1591          str_starts_with( $slug, 'single' ) ||
1592          str_starts_with( $slug, 'page' ) ||
1593          'attachment' === $slug
1594      ) {
1595          $template_hierarchy[] = 'singular';
1596      }
1597      $template_hierarchy[] = 'index';
1598  
1599      $template_type = '';
1600      if ( ! empty( $template_prefix ) ) {
1601          list( $template_type ) = explode( '-', $template_prefix );
1602      } else {
1603          list( $template_type ) = explode( '-', $slug );
1604      }
1605      $valid_template_types = array( '404', 'archive', 'attachment', 'author', 'category', 'date', 'embed', 'frontpage', 'home', 'index', 'page', 'paged', 'privacypolicy', 'search', 'single', 'singular', 'tag', 'taxonomy' );
1606      if ( in_array( $template_type, $valid_template_types, true ) ) {
1607          /** This filter is documented in wp-includes/template.php */
1608          return apply_filters( "{$template_type}_template_hierarchy", $template_hierarchy );
1609      }
1610      return $template_hierarchy;
1611  }
1612  
1613  /**
1614   * Inject ignoredHookedBlocks metadata attributes into a template or template part.
1615   *
1616   * Given an object that represents a `wp_template` or `wp_template_part` post object
1617   * prepared for inserting or updating the database, locate all blocks that have
1618   * hooked blocks, and inject a `metadata.ignoredHookedBlocks` attribute into the anchor
1619   * blocks to reflect the latter.
1620   *
1621   * @since 6.5.0
1622   * @access private
1623   *
1624   * @param stdClass        $changes    An object representing a template or template part
1625   *                                    prepared for inserting or updating the database.
1626   * @param WP_REST_Request $deprecated Deprecated. Not used.
1627   * @return stdClass|WP_Error The updated object representing a template or template part.
1628   */
1629  function inject_ignored_hooked_blocks_metadata_attributes( $changes, $deprecated = null ) {
1630      if ( null !== $deprecated ) {
1631          _deprecated_argument( __FUNCTION__, '6.5.3' );
1632      }
1633  
1634      if ( ! isset( $changes->post_content ) ) {
1635          return $changes;
1636      }
1637  
1638      $hooked_blocks = get_hooked_blocks();
1639      if ( empty( $hooked_blocks ) && ! has_filter( 'hooked_block_types' ) ) {
1640          return $changes;
1641      }
1642  
1643      $meta  = isset( $changes->meta_input ) ? $changes->meta_input : array();
1644      $terms = isset( $changes->tax_input ) ? $changes->tax_input : array();
1645  
1646      if ( empty( $changes->ID ) ) {
1647          // There's no post object for this template in the database for this template yet.
1648          $post = $changes;
1649      } else {
1650          // Find the existing post object.
1651          $post = get_post( $changes->ID );
1652  
1653          // If the post is a revision, use the parent post's post_name and post_type.
1654          $post_id = wp_is_post_revision( $post );
1655          if ( $post_id ) {
1656              $parent_post     = get_post( $post_id );
1657              $post->post_name = $parent_post->post_name;
1658              $post->post_type = $parent_post->post_type;
1659          }
1660  
1661          // Apply the changes to the existing post object.
1662          $post = (object) array_merge( (array) $post, (array) $changes );
1663  
1664          $type_terms        = get_the_terms( $changes->ID, 'wp_theme' );
1665          $terms['wp_theme'] = ! is_wp_error( $type_terms ) && ! empty( $type_terms ) ? $type_terms[0]->name : null;
1666      }
1667  
1668      // Required for the WP_Block_Template. Update the post object with the current time.
1669      $post->post_modified = current_time( 'mysql' );
1670  
1671      // If the post_author is empty, set it to the current user.
1672      if ( empty( $post->post_author ) ) {
1673          $post->post_author = get_current_user_id();
1674      }
1675  
1676      if ( 'wp_template_part' === $post->post_type && ! isset( $terms['wp_template_part_area'] ) ) {
1677          $area_terms                     = get_the_terms( $changes->ID, 'wp_template_part_area' );
1678          $terms['wp_template_part_area'] = ! is_wp_error( $area_terms ) && ! empty( $area_terms ) ? $area_terms[0]->name : null;
1679      }
1680  
1681      $template = _build_block_template_object_from_post_object( new WP_Post( $post ), $terms, $meta );
1682  
1683      if ( is_wp_error( $template ) ) {
1684          return $template;
1685      }
1686  
1687      if ( 'wp_template_part' === $post->post_type ) {
1688          $attributes                     = array();
1689          $existing_ignored_hooked_blocks = isset( $post->ID ) ? get_post_meta( $post->ID, '_wp_ignored_hooked_blocks', true ) : '';
1690  
1691          if ( ! empty( $existing_ignored_hooked_blocks ) ) {
1692              $attributes['metadata'] = array(
1693                  'ignoredHookedBlocks' => json_decode( $existing_ignored_hooked_blocks, true ),
1694              );
1695          }
1696  
1697          $content               = get_comment_delimited_block_content(
1698              'core/template-part',
1699              $attributes,
1700              $changes->post_content
1701          );
1702          $content               = apply_block_hooks_to_content( $content, $template, 'set_ignored_hooked_blocks_metadata' );
1703          $changes->post_content = remove_serialized_parent_block( $content );
1704  
1705          $wrapper_block_markup  = extract_serialized_parent_block( $content );
1706          $wrapper_block         = parse_blocks( $wrapper_block_markup )[0];
1707          $ignored_hooked_blocks = $wrapper_block['attrs']['metadata']['ignoredHookedBlocks'] ?? array();
1708          if ( ! empty( $ignored_hooked_blocks ) ) {
1709              if ( ! isset( $changes->meta_input ) ) {
1710                  $changes->meta_input = array();
1711              }
1712              $changes->meta_input['_wp_ignored_hooked_blocks'] = wp_json_encode( $ignored_hooked_blocks );
1713          }
1714      } else {
1715          $changes->post_content = apply_block_hooks_to_content( $changes->post_content, $template, 'set_ignored_hooked_blocks_metadata' );
1716      }
1717  
1718      return $changes;
1719  }


Generated : Sat Dec 21 08:20:01 2024 Cross-referenced by PHPXref