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


Generated : Mon Jun 15 08:20:09 2026 Cross-referenced by PHPXref