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


Generated : Thu May 9 08:20:02 2024 Cross-referenced by PHPXref