[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Thu Nov 6 08:20:07 2025 Cross-referenced by PHPXref