[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Sun Jul 5 08:20:13 2026 Cross-referenced by PHPXref