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


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