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


Generated : Sun Oct 4 08:20:33 2026 Cross-referenced by PHPXref