block-template-utils.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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. // Define constants for supported wp_template_part_area taxonomy.
  9. if ( ! defined( 'WP_TEMPLATE_PART_AREA_HEADER' ) ) {
  10. define( 'WP_TEMPLATE_PART_AREA_HEADER', 'header' );
  11. }
  12. if ( ! defined( 'WP_TEMPLATE_PART_AREA_FOOTER' ) ) {
  13. define( 'WP_TEMPLATE_PART_AREA_FOOTER', 'footer' );
  14. }
  15. if ( ! defined( 'WP_TEMPLATE_PART_AREA_SIDEBAR' ) ) {
  16. define( 'WP_TEMPLATE_PART_AREA_SIDEBAR', 'sidebar' );
  17. }
  18. if ( ! defined( 'WP_TEMPLATE_PART_AREA_UNCATEGORIZED' ) ) {
  19. define( 'WP_TEMPLATE_PART_AREA_UNCATEGORIZED', 'uncategorized' );
  20. }
  21. /**
  22. * For backward compatibility reasons,
  23. * block themes might be using block-templates or block-template-parts,
  24. * this function ensures we fallback to these folders properly.
  25. *
  26. * @since 5.9.0
  27. *
  28. * @param string $theme_stylesheet The stylesheet. Default is to leverage the main theme root.
  29. *
  30. * @return string[] {
  31. * Folder names used by block themes.
  32. *
  33. * @type string $wp_template Theme-relative directory name for block templates.
  34. * @type string $wp_template_part Theme-relative directory name for block template parts.
  35. * }
  36. */
  37. function get_block_theme_folders( $theme_stylesheet = null ) {
  38. $theme_name = null === $theme_stylesheet ? get_stylesheet() : $theme_stylesheet;
  39. $root_dir = get_theme_root( $theme_name );
  40. $theme_dir = "$root_dir/$theme_name";
  41. if ( file_exists( $theme_dir . '/block-templates' ) || file_exists( $theme_dir . '/block-template-parts' ) ) {
  42. return array(
  43. 'wp_template' => 'block-templates',
  44. 'wp_template_part' => 'block-template-parts',
  45. );
  46. }
  47. return array(
  48. 'wp_template' => 'templates',
  49. 'wp_template_part' => 'parts',
  50. );
  51. }
  52. /**
  53. * Returns a filtered list of allowed area values for template parts.
  54. *
  55. * @since 5.9.0
  56. *
  57. * @return array The supported template part area values.
  58. */
  59. function get_allowed_block_template_part_areas() {
  60. $default_area_definitions = array(
  61. array(
  62. 'area' => WP_TEMPLATE_PART_AREA_UNCATEGORIZED,
  63. 'label' => __( 'General' ),
  64. 'description' => __(
  65. 'General templates often perform a specific role like displaying post content, and are not tied to any particular area.'
  66. ),
  67. 'icon' => 'layout',
  68. 'area_tag' => 'div',
  69. ),
  70. array(
  71. 'area' => WP_TEMPLATE_PART_AREA_HEADER,
  72. 'label' => __( 'Header' ),
  73. 'description' => __(
  74. 'The Header template defines a page area that typically contains a title, logo, and main navigation.'
  75. ),
  76. 'icon' => 'header',
  77. 'area_tag' => 'header',
  78. ),
  79. array(
  80. 'area' => WP_TEMPLATE_PART_AREA_FOOTER,
  81. 'label' => __( 'Footer' ),
  82. 'description' => __(
  83. 'The Footer template defines a page area that typically contains site credits, social links, or any other combination of blocks.'
  84. ),
  85. 'icon' => 'footer',
  86. 'area_tag' => 'footer',
  87. ),
  88. );
  89. /**
  90. * Filters the list of allowed template part area values.
  91. *
  92. * @since 5.9.0
  93. *
  94. * @param array $default_area_definitions An array of supported area objects.
  95. */
  96. return apply_filters( 'default_wp_template_part_areas', $default_area_definitions );
  97. }
  98. /**
  99. * Returns a filtered list of default template types, containing their
  100. * localized titles and descriptions.
  101. *
  102. * @since 5.9.0
  103. *
  104. * @return array The default template types.
  105. */
  106. function get_default_block_template_types() {
  107. $default_template_types = array(
  108. 'index' => array(
  109. 'title' => _x( 'Index', 'Template name' ),
  110. 'description' => __( 'Displays posts.' ),
  111. ),
  112. 'home' => array(
  113. 'title' => _x( 'Home', 'Template name' ),
  114. 'description' => __( 'Displays posts on the homepage, or on the Posts page if a static homepage is set.' ),
  115. ),
  116. 'front-page' => array(
  117. 'title' => _x( 'Front Page', 'Template name' ),
  118. 'description' => __( 'Displays the homepage.' ),
  119. ),
  120. 'singular' => array(
  121. 'title' => _x( 'Singular', 'Template name' ),
  122. 'description' => __( 'Displays a single post or page.' ),
  123. ),
  124. 'single' => array(
  125. 'title' => _x( 'Single', 'Template name' ),
  126. 'description' => __( 'The default template for displaying any single post or attachment.' ),
  127. ),
  128. 'page' => array(
  129. 'title' => _x( 'Page', 'Template name' ),
  130. 'description' => __( 'Displays a single page.' ),
  131. ),
  132. 'archive' => array(
  133. 'title' => _x( 'Archive', 'Template name' ),
  134. 'description' => __( 'Displays post categories, tags, and other archives.' ),
  135. ),
  136. 'author' => array(
  137. 'title' => _x( 'Author', 'Template name' ),
  138. 'description' => __( 'Displays latest posts written by a single author.' ),
  139. ),
  140. 'category' => array(
  141. 'title' => _x( 'Category', 'Template name' ),
  142. 'description' => __( 'Displays latest posts from a single post category.' ),
  143. ),
  144. 'taxonomy' => array(
  145. 'title' => _x( 'Taxonomy', 'Template name' ),
  146. 'description' => __( 'Displays latest posts from a single post taxonomy.' ),
  147. ),
  148. 'date' => array(
  149. 'title' => _x( 'Date', 'Template name' ),
  150. 'description' => __( 'Displays posts from a specific date.' ),
  151. ),
  152. 'tag' => array(
  153. 'title' => _x( 'Tag', 'Template name' ),
  154. 'description' => __( 'Displays latest posts with a single post tag.' ),
  155. ),
  156. 'attachment' => array(
  157. 'title' => __( 'Media' ),
  158. 'description' => __( 'Displays individual media items or attachments.' ),
  159. ),
  160. 'search' => array(
  161. 'title' => _x( 'Search', 'Template name' ),
  162. 'description' => __( 'Displays search results.' ),
  163. ),
  164. 'privacy-policy' => array(
  165. 'title' => __( 'Privacy Policy' ),
  166. 'description' => __( 'Displays the privacy policy page.' ),
  167. ),
  168. '404' => array(
  169. 'title' => _x( '404', 'Template name' ),
  170. 'description' => __( 'Displays when no content is found.' ),
  171. ),
  172. );
  173. /**
  174. * Filters the list of template types.
  175. *
  176. * @since 5.9.0
  177. *
  178. * @param array $default_template_types An array of template types, formatted as [ slug => [ title, description ] ].
  179. */
  180. return apply_filters( 'default_template_types', $default_template_types );
  181. }
  182. /**
  183. * Checks whether the input 'area' is a supported value.
  184. * Returns the input if supported, otherwise returns the 'uncategorized' value.
  185. *
  186. * @since 5.9.0
  187. * @access private
  188. *
  189. * @param string $type Template part area name.
  190. * @return string Input if supported, else the uncategorized value.
  191. */
  192. function _filter_block_template_part_area( $type ) {
  193. $allowed_areas = array_map(
  194. static function ( $item ) {
  195. return $item['area'];
  196. },
  197. get_allowed_block_template_part_areas()
  198. );
  199. if ( in_array( $type, $allowed_areas, true ) ) {
  200. return $type;
  201. }
  202. $warning_message = sprintf(
  203. /* translators: %1$s: Template area type, %2$s: the uncategorized template area value. */
  204. __( '"%1$s" is not a supported wp_template_part area value and has been added as "%2$s".' ),
  205. $type,
  206. WP_TEMPLATE_PART_AREA_UNCATEGORIZED
  207. );
  208. trigger_error( $warning_message, E_USER_NOTICE );
  209. return WP_TEMPLATE_PART_AREA_UNCATEGORIZED;
  210. }
  211. /**
  212. * Finds all nested template part file paths in a theme's directory.
  213. *
  214. * @since 5.9.0
  215. * @access private
  216. *
  217. * @param string $base_directory The theme's file path.
  218. * @return array A list of paths to all template part files.
  219. */
  220. function _get_block_templates_paths( $base_directory ) {
  221. $path_list = array();
  222. if ( file_exists( $base_directory ) ) {
  223. $nested_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base_directory ) );
  224. $nested_html_files = new RegexIterator( $nested_files, '/^.+\.html$/i', RecursiveRegexIterator::GET_MATCH );
  225. foreach ( $nested_html_files as $path => $file ) {
  226. $path_list[] = $path;
  227. }
  228. }
  229. return $path_list;
  230. }
  231. /**
  232. * Retrieves the template file from the theme for a given slug.
  233. *
  234. * @since 5.9.0
  235. * @access private
  236. *
  237. * @param string $template_type 'wp_template' or 'wp_template_part'.
  238. * @param string $slug Template slug.
  239. * @return array|null Template.
  240. */
  241. function _get_block_template_file( $template_type, $slug ) {
  242. if ( 'wp_template' !== $template_type && 'wp_template_part' !== $template_type ) {
  243. return null;
  244. }
  245. $themes = array(
  246. get_stylesheet() => get_stylesheet_directory(),
  247. get_template() => get_template_directory(),
  248. );
  249. foreach ( $themes as $theme_slug => $theme_dir ) {
  250. $template_base_paths = get_block_theme_folders( $theme_slug );
  251. $file_path = $theme_dir . '/' . $template_base_paths[ $template_type ] . '/' . $slug . '.html';
  252. if ( file_exists( $file_path ) ) {
  253. $new_template_item = array(
  254. 'slug' => $slug,
  255. 'path' => $file_path,
  256. 'theme' => $theme_slug,
  257. 'type' => $template_type,
  258. );
  259. if ( 'wp_template_part' === $template_type ) {
  260. return _add_block_template_part_area_info( $new_template_item );
  261. }
  262. if ( 'wp_template' === $template_type ) {
  263. return _add_block_template_info( $new_template_item );
  264. }
  265. return $new_template_item;
  266. }
  267. }
  268. return null;
  269. }
  270. /**
  271. * Retrieves the template files from the theme.
  272. *
  273. * @since 5.9.0
  274. * @access private
  275. *
  276. * @param string $template_type 'wp_template' or 'wp_template_part'.
  277. * @return array Template.
  278. */
  279. function _get_block_templates_files( $template_type ) {
  280. if ( 'wp_template' !== $template_type && 'wp_template_part' !== $template_type ) {
  281. return null;
  282. }
  283. $themes = array(
  284. get_stylesheet() => get_stylesheet_directory(),
  285. get_template() => get_template_directory(),
  286. );
  287. $template_files = array();
  288. foreach ( $themes as $theme_slug => $theme_dir ) {
  289. $template_base_paths = get_block_theme_folders( $theme_slug );
  290. $theme_template_files = _get_block_templates_paths( $theme_dir . '/' . $template_base_paths[ $template_type ] );
  291. foreach ( $theme_template_files as $template_file ) {
  292. $template_base_path = $template_base_paths[ $template_type ];
  293. $template_slug = substr(
  294. $template_file,
  295. // Starting position of slug.
  296. strpos( $template_file, $template_base_path . DIRECTORY_SEPARATOR ) + 1 + strlen( $template_base_path ),
  297. // Subtract ending '.html'.
  298. -5
  299. );
  300. $new_template_item = array(
  301. 'slug' => $template_slug,
  302. 'path' => $template_file,
  303. 'theme' => $theme_slug,
  304. 'type' => $template_type,
  305. );
  306. if ( 'wp_template_part' === $template_type ) {
  307. $template_files[] = _add_block_template_part_area_info( $new_template_item );
  308. }
  309. if ( 'wp_template' === $template_type ) {
  310. $template_files[] = _add_block_template_info( $new_template_item );
  311. }
  312. }
  313. }
  314. return $template_files;
  315. }
  316. /**
  317. * Attempts to add custom template information to the template item.
  318. *
  319. * @since 5.9.0
  320. * @access private
  321. *
  322. * @param array $template_item Template to add information to (requires 'slug' field).
  323. * @return array Template item.
  324. */
  325. function _add_block_template_info( $template_item ) {
  326. if ( ! WP_Theme_JSON_Resolver::theme_has_support() ) {
  327. return $template_item;
  328. }
  329. $theme_data = WP_Theme_JSON_Resolver::get_theme_data()->get_custom_templates();
  330. if ( isset( $theme_data[ $template_item['slug'] ] ) ) {
  331. $template_item['title'] = $theme_data[ $template_item['slug'] ]['title'];
  332. $template_item['postTypes'] = $theme_data[ $template_item['slug'] ]['postTypes'];
  333. }
  334. return $template_item;
  335. }
  336. /**
  337. * Attempts to add the template part's area information to the input template.
  338. *
  339. * @since 5.9.0
  340. * @access private
  341. *
  342. * @param array $template_info Template to add information to (requires 'type' and 'slug' fields).
  343. * @return array Template info.
  344. */
  345. function _add_block_template_part_area_info( $template_info ) {
  346. if ( WP_Theme_JSON_Resolver::theme_has_support() ) {
  347. $theme_data = WP_Theme_JSON_Resolver::get_theme_data()->get_template_parts();
  348. }
  349. if ( isset( $theme_data[ $template_info['slug'] ]['area'] ) ) {
  350. $template_info['title'] = $theme_data[ $template_info['slug'] ]['title'];
  351. $template_info['area'] = _filter_block_template_part_area( $theme_data[ $template_info['slug'] ]['area'] );
  352. } else {
  353. $template_info['area'] = WP_TEMPLATE_PART_AREA_UNCATEGORIZED;
  354. }
  355. return $template_info;
  356. }
  357. /**
  358. * Returns an array containing the references of
  359. * the passed blocks and their inner blocks.
  360. *
  361. * @since 5.9.0
  362. * @access private
  363. *
  364. * @param array $blocks array of blocks.
  365. * @return array block references to the passed blocks and their inner blocks.
  366. */
  367. function _flatten_blocks( &$blocks ) {
  368. $all_blocks = array();
  369. $queue = array();
  370. foreach ( $blocks as &$block ) {
  371. $queue[] = &$block;
  372. }
  373. while ( count( $queue ) > 0 ) {
  374. $block = &$queue[0];
  375. array_shift( $queue );
  376. $all_blocks[] = &$block;
  377. if ( ! empty( $block['innerBlocks'] ) ) {
  378. foreach ( $block['innerBlocks'] as &$inner_block ) {
  379. $queue[] = &$inner_block;
  380. }
  381. }
  382. }
  383. return $all_blocks;
  384. }
  385. /**
  386. * Parses wp_template content and injects the active theme's
  387. * stylesheet as a theme attribute into each wp_template_part
  388. *
  389. * @since 5.9.0
  390. * @access private
  391. *
  392. * @param string $template_content serialized wp_template content.
  393. * @return string Updated 'wp_template' content.
  394. */
  395. function _inject_theme_attribute_in_block_template_content( $template_content ) {
  396. $has_updated_content = false;
  397. $new_content = '';
  398. $template_blocks = parse_blocks( $template_content );
  399. $blocks = _flatten_blocks( $template_blocks );
  400. foreach ( $blocks as &$block ) {
  401. if (
  402. 'core/template-part' === $block['blockName'] &&
  403. ! isset( $block['attrs']['theme'] )
  404. ) {
  405. $block['attrs']['theme'] = get_stylesheet();
  406. $has_updated_content = true;
  407. }
  408. }
  409. if ( $has_updated_content ) {
  410. foreach ( $template_blocks as &$block ) {
  411. $new_content .= serialize_block( $block );
  412. }
  413. return $new_content;
  414. }
  415. return $template_content;
  416. }
  417. /**
  418. * Parses a block template and removes the theme attribute from each template part.
  419. *
  420. * @since 5.9.0
  421. * @access private
  422. *
  423. * @param string $template_content Serialized block template content.
  424. * @return string Updated block template content.
  425. */
  426. function _remove_theme_attribute_in_block_template_content( $template_content ) {
  427. $has_updated_content = false;
  428. $new_content = '';
  429. $template_blocks = parse_blocks( $template_content );
  430. $blocks = _flatten_blocks( $template_blocks );
  431. foreach ( $blocks as $key => $block ) {
  432. if ( 'core/template-part' === $block['blockName'] && isset( $block['attrs']['theme'] ) ) {
  433. unset( $blocks[ $key ]['attrs']['theme'] );
  434. $has_updated_content = true;
  435. }
  436. }
  437. if ( ! $has_updated_content ) {
  438. return $template_content;
  439. }
  440. foreach ( $template_blocks as $block ) {
  441. $new_content .= serialize_block( $block );
  442. }
  443. return $new_content;
  444. }
  445. /**
  446. * Builds a unified template object based on a theme file.
  447. *
  448. * @since 5.9.0
  449. * @access private
  450. *
  451. * @param array $template_file Theme file.
  452. * @param string $template_type 'wp_template' or 'wp_template_part'.
  453. * @return WP_Block_Template Template.
  454. */
  455. function _build_block_template_result_from_file( $template_file, $template_type ) {
  456. $default_template_types = get_default_block_template_types();
  457. $template_content = file_get_contents( $template_file['path'] );
  458. $theme = get_stylesheet();
  459. $template = new WP_Block_Template();
  460. $template->id = $theme . '//' . $template_file['slug'];
  461. $template->theme = $theme;
  462. $template->content = _inject_theme_attribute_in_block_template_content( $template_content );
  463. $template->slug = $template_file['slug'];
  464. $template->source = 'theme';
  465. $template->type = $template_type;
  466. $template->title = ! empty( $template_file['title'] ) ? $template_file['title'] : $template_file['slug'];
  467. $template->status = 'publish';
  468. $template->has_theme_file = true;
  469. $template->is_custom = true;
  470. if ( 'wp_template' === $template_type && isset( $default_template_types[ $template_file['slug'] ] ) ) {
  471. $template->description = $default_template_types[ $template_file['slug'] ]['description'];
  472. $template->title = $default_template_types[ $template_file['slug'] ]['title'];
  473. $template->is_custom = false;
  474. }
  475. if ( 'wp_template' === $template_type && isset( $template_file['postTypes'] ) ) {
  476. $template->post_types = $template_file['postTypes'];
  477. }
  478. if ( 'wp_template_part' === $template_type && isset( $template_file['area'] ) ) {
  479. $template->area = $template_file['area'];
  480. }
  481. return $template;
  482. }
  483. /**
  484. * Builds the title and description of a post-specific template based on the underlying referenced post.
  485. *
  486. * Mutates the underlying template object.
  487. *
  488. * @since 6.1.0
  489. * @access private
  490. *
  491. * @param string $post_type Post type, e.g. page, post, product.
  492. * @param string $slug Slug of the post, e.g. a-story-about-shoes.
  493. * @param WP_Block_Template $template Template to mutate adding the description and title computed.
  494. * @return bool Returns true if the referenced post was found and false otherwise.
  495. */
  496. function _wp_build_title_and_description_for_single_post_type_block_template( $post_type, $slug, WP_Block_Template $template ) {
  497. $post_type_object = get_post_type_object( $post_type );
  498. $default_args = array(
  499. 'post_type' => $post_type,
  500. 'post_status' => 'publish',
  501. 'posts_per_page' => 1,
  502. 'update_post_meta_cache' => false,
  503. 'update_post_term_cache' => false,
  504. 'ignore_sticky_posts' => true,
  505. 'no_found_rows' => true,
  506. );
  507. $args = array(
  508. 'name' => $slug,
  509. );
  510. $args = wp_parse_args( $args, $default_args );
  511. $posts_query = new WP_Query( $args );
  512. if ( empty( $posts_query->posts ) ) {
  513. $template->title = sprintf(
  514. /* translators: Custom template title in the Site Editor referencing a post that was not found. 1: Post type singular name, 2: Post type slug. */
  515. __( 'Not found: %1$s (%2$s)' ),
  516. $post_type_object->labels->singular_name,
  517. $slug
  518. );
  519. return false;
  520. }
  521. $post_title = $posts_query->posts[0]->post_title;
  522. $template->title = sprintf(
  523. /* translators: Custom template title in the Site Editor. 1: Post type singular name, 2: Post title. */
  524. __( '%1$s: %2$s' ),
  525. $post_type_object->labels->singular_name,
  526. $post_title
  527. );
  528. $template->description = sprintf(
  529. /* translators: Custom template description in the Site Editor. %s: Post title. */
  530. __( 'Template for %s' ),
  531. $post_title
  532. );
  533. $args = array(
  534. 'title' => $post_title,
  535. );
  536. $args = wp_parse_args( $args, $default_args );
  537. $posts_with_same_title_query = new WP_Query( $args );
  538. if ( count( $posts_with_same_title_query->posts ) > 1 ) {
  539. $template->title = sprintf(
  540. /* translators: Custom template title in the Site Editor. 1: Template title, 2: Post type slug. */
  541. __( '%1$s (%2$s)' ),
  542. $template->title,
  543. $slug
  544. );
  545. }
  546. return true;
  547. }
  548. /**
  549. * Builds the title and description of a taxonomy-specific template based on the underlying entity referenced.
  550. *
  551. * Mutates the underlying template object.
  552. *
  553. * @since 6.1.0
  554. * @access private
  555. *
  556. * @param string $taxonomy Identifier of the taxonomy, e.g. category.
  557. * @param string $slug Slug of the term, e.g. shoes.
  558. * @param WP_Block_Template $template Template to mutate adding the description and title computed.
  559. * @return bool True if the term referenced was found and false otherwise.
  560. */
  561. function _wp_build_title_and_description_for_taxonomy_block_template( $taxonomy, $slug, WP_Block_Template $template ) {
  562. $taxonomy_object = get_taxonomy( $taxonomy );
  563. $default_args = array(
  564. 'taxonomy' => $taxonomy,
  565. 'hide_empty' => false,
  566. 'update_term_meta_cache' => false,
  567. );
  568. $term_query = new WP_Term_Query();
  569. $args = array(
  570. 'number' => 1,
  571. 'slug' => $slug,
  572. );
  573. $args = wp_parse_args( $args, $default_args );
  574. $terms_query = $term_query->query( $args );
  575. if ( empty( $terms_query ) ) {
  576. $template->title = sprintf(
  577. /* translators: Custom template title in the Site Editor, referencing a taxonomy term that was not found. 1: Taxonomy singular name, 2: Term slug. */
  578. __( 'Not found: %1$s (%2$s)' ),
  579. $taxonomy_object->labels->singular_name,
  580. $slug
  581. );
  582. return false;
  583. }
  584. $term_title = $terms_query[0]->name;
  585. $template->title = sprintf(
  586. /* translators: Custom template title in the Site Editor. 1: Taxonomy singular name, 2: Term title. */
  587. __( '%1$s: %2$s' ),
  588. $taxonomy_object->labels->singular_name,
  589. $term_title
  590. );
  591. $template->description = sprintf(
  592. /* translators: Custom template description in the Site Editor. %s: Term title. */
  593. __( 'Template for %s' ),
  594. $term_title
  595. );
  596. $term_query = new WP_Term_Query();
  597. $args = array(
  598. 'number' => 2,
  599. 'name' => $term_title,
  600. );
  601. $args = wp_parse_args( $args, $default_args );
  602. $terms_with_same_title_query = $term_query->query( $args );
  603. if ( count( $terms_with_same_title_query ) > 1 ) {
  604. $template->title = sprintf(
  605. /* translators: Custom template title in the Site Editor. 1: Template title, 2: Term slug. */
  606. __( '%1$s (%2$s)' ),
  607. $template->title,
  608. $slug
  609. );
  610. }
  611. return true;
  612. }
  613. /**
  614. * Builds a unified template object based a post Object.
  615. *
  616. * @since 5.9.0
  617. * @access private
  618. *
  619. * @param WP_Post $post Template post.
  620. * @return WP_Block_Template|WP_Error Template.
  621. */
  622. function _build_block_template_result_from_post( $post ) {
  623. $default_template_types = get_default_block_template_types();
  624. $terms = get_the_terms( $post, 'wp_theme' );
  625. if ( is_wp_error( $terms ) ) {
  626. return $terms;
  627. }
  628. if ( ! $terms ) {
  629. return new WP_Error( 'template_missing_theme', __( 'No theme is defined for this template.' ) );
  630. }
  631. $theme = $terms[0]->name;
  632. $template_file = _get_block_template_file( $post->post_type, $post->post_name );
  633. $has_theme_file = get_stylesheet() === $theme && null !== $template_file;
  634. $origin = get_post_meta( $post->ID, 'origin', true );
  635. $is_wp_suggestion = get_post_meta( $post->ID, 'is_wp_suggestion', true );
  636. $template = new WP_Block_Template();
  637. $template->wp_id = $post->ID;
  638. $template->id = $theme . '//' . $post->post_name;
  639. $template->theme = $theme;
  640. $template->content = $post->post_content;
  641. $template->slug = $post->post_name;
  642. $template->source = 'custom';
  643. $template->origin = ! empty( $origin ) ? $origin : null;
  644. $template->type = $post->post_type;
  645. $template->description = $post->post_excerpt;
  646. $template->title = $post->post_title;
  647. $template->status = $post->post_status;
  648. $template->has_theme_file = $has_theme_file;
  649. $template->is_custom = empty( $is_wp_suggestion );
  650. $template->author = $post->post_author;
  651. if ( 'wp_template' === $post->post_type && $has_theme_file && isset( $template_file['postTypes'] ) ) {
  652. $template->post_types = $template_file['postTypes'];
  653. }
  654. if ( 'wp_template' === $post->post_type && isset( $default_template_types[ $template->slug ] ) ) {
  655. $template->is_custom = false;
  656. }
  657. if ( 'wp_template_part' === $post->post_type ) {
  658. $type_terms = get_the_terms( $post, 'wp_template_part_area' );
  659. if ( ! is_wp_error( $type_terms ) && false !== $type_terms ) {
  660. $template->area = $type_terms[0]->name;
  661. }
  662. }
  663. // Check for a block template without a description and title or with a title equal to the slug.
  664. if ( 'wp_template' === $post->post_type && empty( $template->description ) && ( empty( $template->title ) || $template->title === $template->slug ) ) {
  665. $matches = array();
  666. // Check for a block template for a single author, page, post, tag, category, custom post type, or custom taxonomy.
  667. if ( preg_match( '/(author|page|single|tag|category|taxonomy)-(.+)/', $template->slug, $matches ) ) {
  668. $type = $matches[1];
  669. $slug_remaining = $matches[2];
  670. switch ( $type ) {
  671. case 'author':
  672. $nice_name = $slug_remaining;
  673. $users = get_users(
  674. array(
  675. 'capability' => 'edit_posts',
  676. 'search' => $nice_name,
  677. 'search_columns' => array( 'user_nicename' ),
  678. 'fields' => 'display_name',
  679. )
  680. );
  681. if ( empty( $users ) ) {
  682. $template->title = sprintf(
  683. /* translators: Custom template title in the Site Editor, referencing a deleted author. %s: Author nicename. */
  684. __( 'Deleted author: %s' ),
  685. $nice_name
  686. );
  687. } else {
  688. $author_name = $users[0];
  689. $template->title = sprintf(
  690. /* translators: Custom template title in the Site Editor. %s: Author name. */
  691. __( 'Author: %s' ),
  692. $author_name
  693. );
  694. $template->description = sprintf(
  695. /* translators: Custom template description in the Site Editor. %s: Author name. */
  696. __( 'Template for %s' ),
  697. $author_name
  698. );
  699. $users_with_same_name = get_users(
  700. array(
  701. 'capability' => 'edit_posts',
  702. 'search' => $author_name,
  703. 'search_columns' => array( 'display_name' ),
  704. 'fields' => 'display_name',
  705. )
  706. );
  707. if ( count( $users_with_same_name ) > 1 ) {
  708. $template->title = sprintf(
  709. /* translators: Custom template title in the Site Editor. 1: Template title of an author template, 2: Author nicename. */
  710. __( '%1$s (%2$s)' ),
  711. $template->title,
  712. $nice_name
  713. );
  714. }
  715. }
  716. break;
  717. case 'page':
  718. _wp_build_title_and_description_for_single_post_type_block_template( 'page', $slug_remaining, $template );
  719. break;
  720. case 'single':
  721. $post_types = get_post_types();
  722. foreach ( $post_types as $post_type ) {
  723. $post_type_length = strlen( $post_type ) + 1;
  724. // If $slug_remaining starts with $post_type followed by a hyphen.
  725. if ( 0 === strncmp( $slug_remaining, $post_type . '-', $post_type_length ) ) {
  726. $slug = substr( $slug_remaining, $post_type_length, strlen( $slug_remaining ) );
  727. $found = _wp_build_title_and_description_for_single_post_type_block_template( $post_type, $slug, $template );
  728. if ( $found ) {
  729. break;
  730. }
  731. }
  732. }
  733. break;
  734. case 'tag':
  735. _wp_build_title_and_description_for_taxonomy_block_template( 'post_tag', $slug_remaining, $template );
  736. break;
  737. case 'category':
  738. _wp_build_title_and_description_for_taxonomy_block_template( 'category', $slug_remaining, $template );
  739. break;
  740. case 'taxonomy':
  741. $taxonomies = get_taxonomies();
  742. foreach ( $taxonomies as $taxonomy ) {
  743. $taxonomy_length = strlen( $taxonomy ) + 1;
  744. // If $slug_remaining starts with $taxonomy followed by a hyphen.
  745. if ( 0 === strncmp( $slug_remaining, $taxonomy . '-', $taxonomy_length ) ) {
  746. $slug = substr( $slug_remaining, $taxonomy_length, strlen( $slug_remaining ) );
  747. $found = _wp_build_title_and_description_for_taxonomy_block_template( $taxonomy, $slug, $template );
  748. if ( $found ) {
  749. break;
  750. }
  751. }
  752. }
  753. break;
  754. }
  755. }
  756. }
  757. return $template;
  758. }
  759. /**
  760. * Retrieves a list of unified template objects based on a query.
  761. *
  762. * @since 5.8.0
  763. *
  764. * @param array $query {
  765. * Optional. Arguments to retrieve templates.
  766. *
  767. * @type array $slug__in List of slugs to include.
  768. * @type int $wp_id Post ID of customized template.
  769. * @type string $area A 'wp_template_part_area' taxonomy value to filter by (for wp_template_part template type only).
  770. * @type string $post_type Post type to get the templates for.
  771. * }
  772. * @param string $template_type 'wp_template' or 'wp_template_part'.
  773. * @return array Templates.
  774. */
  775. function get_block_templates( $query = array(), $template_type = 'wp_template' ) {
  776. /**
  777. * Filters the block templates array before the query takes place.
  778. *
  779. * Return a non-null value to bypass the WordPress queries.
  780. *
  781. * @since 5.9.0
  782. *
  783. * @param WP_Block_Template[]|null $block_templates Return an array of block templates to short-circuit the default query,
  784. * or null to allow WP to run it's normal queries.
  785. * @param array $query {
  786. * Optional. Arguments to retrieve templates.
  787. *
  788. * @type array $slug__in List of slugs to include.
  789. * @type int $wp_id Post ID of customized template.
  790. * @type string $post_type Post type to get the templates for.
  791. * }
  792. * @param string $template_type wp_template or wp_template_part.
  793. */
  794. $templates = apply_filters( 'pre_get_block_templates', null, $query, $template_type );
  795. if ( ! is_null( $templates ) ) {
  796. return $templates;
  797. }
  798. $post_type = isset( $query['post_type'] ) ? $query['post_type'] : '';
  799. $wp_query_args = array(
  800. 'post_status' => array( 'auto-draft', 'draft', 'publish' ),
  801. 'post_type' => $template_type,
  802. 'posts_per_page' => -1,
  803. 'no_found_rows' => true,
  804. 'tax_query' => array(
  805. array(
  806. 'taxonomy' => 'wp_theme',
  807. 'field' => 'name',
  808. 'terms' => get_stylesheet(),
  809. ),
  810. ),
  811. );
  812. if ( 'wp_template_part' === $template_type && isset( $query['area'] ) ) {
  813. $wp_query_args['tax_query'][] = array(
  814. 'taxonomy' => 'wp_template_part_area',
  815. 'field' => 'name',
  816. 'terms' => $query['area'],
  817. );
  818. $wp_query_args['tax_query']['relation'] = 'AND';
  819. }
  820. if ( isset( $query['slug__in'] ) ) {
  821. $wp_query_args['post_name__in'] = $query['slug__in'];
  822. }
  823. // This is only needed for the regular templates/template parts post type listing and editor.
  824. if ( isset( $query['wp_id'] ) ) {
  825. $wp_query_args['p'] = $query['wp_id'];
  826. } else {
  827. $wp_query_args['post_status'] = 'publish';
  828. }
  829. $template_query = new WP_Query( $wp_query_args );
  830. $query_result = array();
  831. foreach ( $template_query->posts as $post ) {
  832. $template = _build_block_template_result_from_post( $post );
  833. if ( is_wp_error( $template ) ) {
  834. continue;
  835. }
  836. if ( $post_type && ! $template->is_custom ) {
  837. continue;
  838. }
  839. if (
  840. $post_type &&
  841. isset( $template->post_types ) &&
  842. ! in_array( $post_type, $template->post_types, true )
  843. ) {
  844. continue;
  845. }
  846. $query_result[] = $template;
  847. }
  848. if ( ! isset( $query['wp_id'] ) ) {
  849. $template_files = _get_block_templates_files( $template_type );
  850. foreach ( $template_files as $template_file ) {
  851. $template = _build_block_template_result_from_file( $template_file, $template_type );
  852. if ( $post_type && ! $template->is_custom ) {
  853. continue;
  854. }
  855. if ( $post_type &&
  856. isset( $template->post_types ) &&
  857. ! in_array( $post_type, $template->post_types, true )
  858. ) {
  859. continue;
  860. }
  861. $is_not_custom = false === array_search(
  862. get_stylesheet() . '//' . $template_file['slug'],
  863. wp_list_pluck( $query_result, 'id' ),
  864. true
  865. );
  866. $fits_slug_query =
  867. ! isset( $query['slug__in'] ) || in_array( $template_file['slug'], $query['slug__in'], true );
  868. $fits_area_query =
  869. ! isset( $query['area'] ) || $template_file['area'] === $query['area'];
  870. $should_include = $is_not_custom && $fits_slug_query && $fits_area_query;
  871. if ( $should_include ) {
  872. $query_result[] = $template;
  873. }
  874. }
  875. }
  876. /**
  877. * Filters the array of queried block templates array after they've been fetched.
  878. *
  879. * @since 5.9.0
  880. *
  881. * @param WP_Block_Template[] $query_result Array of found block templates.
  882. * @param array $query {
  883. * Optional. Arguments to retrieve templates.
  884. *
  885. * @type array $slug__in List of slugs to include.
  886. * @type int $wp_id Post ID of customized template.
  887. * }
  888. * @param string $template_type wp_template or wp_template_part.
  889. */
  890. return apply_filters( 'get_block_templates', $query_result, $query, $template_type );
  891. }
  892. /**
  893. * Retrieves a single unified template object using its id.
  894. *
  895. * @since 5.8.0
  896. *
  897. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  898. * @param string $template_type Optional. Template type: `'wp_template'` or '`wp_template_part'`.
  899. * Default `'wp_template'`.
  900. * @return WP_Block_Template|null Template.
  901. */
  902. function get_block_template( $id, $template_type = 'wp_template' ) {
  903. /**
  904. * Filters the block template object before the query takes place.
  905. *
  906. * Return a non-null value to bypass the WordPress queries.
  907. *
  908. * @since 5.9.0
  909. *
  910. * @param WP_Block_Template|null $block_template Return block template object to short-circuit the default query,
  911. * or null to allow WP to run its normal queries.
  912. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  913. * @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  914. */
  915. $block_template = apply_filters( 'pre_get_block_template', null, $id, $template_type );
  916. if ( ! is_null( $block_template ) ) {
  917. return $block_template;
  918. }
  919. $parts = explode( '//', $id, 2 );
  920. if ( count( $parts ) < 2 ) {
  921. return null;
  922. }
  923. list( $theme, $slug ) = $parts;
  924. $wp_query_args = array(
  925. 'post_name__in' => array( $slug ),
  926. 'post_type' => $template_type,
  927. 'post_status' => array( 'auto-draft', 'draft', 'publish', 'trash' ),
  928. 'posts_per_page' => 1,
  929. 'no_found_rows' => true,
  930. 'tax_query' => array(
  931. array(
  932. 'taxonomy' => 'wp_theme',
  933. 'field' => 'name',
  934. 'terms' => $theme,
  935. ),
  936. ),
  937. );
  938. $template_query = new WP_Query( $wp_query_args );
  939. $posts = $template_query->posts;
  940. if ( count( $posts ) > 0 ) {
  941. $template = _build_block_template_result_from_post( $posts[0] );
  942. if ( ! is_wp_error( $template ) ) {
  943. return $template;
  944. }
  945. }
  946. $block_template = get_block_file_template( $id, $template_type );
  947. /**
  948. * Filters the queried block template object after it's been fetched.
  949. *
  950. * @since 5.9.0
  951. *
  952. * @param WP_Block_Template|null $block_template The found block template, or null if there isn't one.
  953. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  954. * @param array $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  955. */
  956. return apply_filters( 'get_block_template', $block_template, $id, $template_type );
  957. }
  958. /**
  959. * Retrieves a unified template object based on a theme file.
  960. *
  961. * This is a fallback of get_block_template(), used when no templates are found in the database.
  962. *
  963. * @since 5.9.0
  964. *
  965. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  966. * @param string $template_type Optional. Template type: `'wp_template'` or '`wp_template_part'`.
  967. * Default `'wp_template'`.
  968. * @return WP_Block_Template|null The found block template, or null if there isn't one.
  969. */
  970. function get_block_file_template( $id, $template_type = 'wp_template' ) {
  971. /**
  972. * Filters the block template object before the theme file discovery takes place.
  973. *
  974. * Return a non-null value to bypass the WordPress theme file discovery.
  975. *
  976. * @since 5.9.0
  977. *
  978. * @param WP_Block_Template|null $block_template Return block template object to short-circuit the default query,
  979. * or null to allow WP to run its normal queries.
  980. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  981. * @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  982. */
  983. $block_template = apply_filters( 'pre_get_block_file_template', null, $id, $template_type );
  984. if ( ! is_null( $block_template ) ) {
  985. return $block_template;
  986. }
  987. $parts = explode( '//', $id, 2 );
  988. if ( count( $parts ) < 2 ) {
  989. /** This filter is documented in wp-includes/block-template-utils.php */
  990. return apply_filters( 'get_block_file_template', null, $id, $template_type );
  991. }
  992. list( $theme, $slug ) = $parts;
  993. if ( get_stylesheet() !== $theme ) {
  994. /** This filter is documented in wp-includes/block-template-utils.php */
  995. return apply_filters( 'get_block_file_template', null, $id, $template_type );
  996. }
  997. $template_file = _get_block_template_file( $template_type, $slug );
  998. if ( null === $template_file ) {
  999. /** This filter is documented in wp-includes/block-template-utils.php */
  1000. return apply_filters( 'get_block_file_template', null, $id, $template_type );
  1001. }
  1002. $block_template = _build_block_template_result_from_file( $template_file, $template_type );
  1003. /**
  1004. * Filters the block template object after it has been (potentially) fetched from the theme file.
  1005. *
  1006. * @since 5.9.0
  1007. *
  1008. * @param WP_Block_Template|null $block_template The found block template, or null if there is none.
  1009. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  1010. * @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  1011. */
  1012. return apply_filters( 'get_block_file_template', $block_template, $id, $template_type );
  1013. }
  1014. /**
  1015. * Prints a block template part.
  1016. *
  1017. * @since 5.9.0
  1018. *
  1019. * @param string $part The block template part to print. Use "header" or "footer".
  1020. */
  1021. function block_template_part( $part ) {
  1022. $template_part = get_block_template( get_stylesheet() . '//' . $part, 'wp_template_part' );
  1023. if ( ! $template_part || empty( $template_part->content ) ) {
  1024. return;
  1025. }
  1026. echo do_blocks( $template_part->content );
  1027. }
  1028. /**
  1029. * Prints the header block template part.
  1030. *
  1031. * @since 5.9.0
  1032. */
  1033. function block_header_area() {
  1034. block_template_part( 'header' );
  1035. }
  1036. /**
  1037. * Prints the footer block template part.
  1038. *
  1039. * @since 5.9.0
  1040. */
  1041. function block_footer_area() {
  1042. block_template_part( 'footer' );
  1043. }
  1044. /**
  1045. * Determines whether a theme directory should be ignored during export.
  1046. *
  1047. * @since 6.0.0
  1048. *
  1049. * @param string $path The path of the file in the theme.
  1050. * @return Bool Whether this file is in an ignored directory.
  1051. */
  1052. function wp_is_theme_directory_ignored( $path ) {
  1053. $directories_to_ignore = array( '.DS_Store', '.svn', '.git', '.hg', '.bzr', 'node_modules', 'vendor' );
  1054. foreach ( $directories_to_ignore as $directory ) {
  1055. if ( str_starts_with( $path, $directory ) ) {
  1056. return true;
  1057. }
  1058. }
  1059. return false;
  1060. }
  1061. /**
  1062. * Creates an export of the current templates and
  1063. * template parts from the site editor at the
  1064. * specified path in a ZIP file.
  1065. *
  1066. * @since 5.9.0
  1067. * @since 6.0.0 Adds the whole theme to the export archive.
  1068. *
  1069. * @return WP_Error|string Path of the ZIP file or error on failure.
  1070. */
  1071. function wp_generate_block_templates_export_file() {
  1072. if ( ! class_exists( 'ZipArchive' ) ) {
  1073. return new WP_Error( 'missing_zip_package', __( 'Zip Export not supported.' ) );
  1074. }
  1075. $obscura = wp_generate_password( 12, false, false );
  1076. $theme_name = basename( get_stylesheet() );
  1077. $filename = get_temp_dir() . $theme_name . $obscura . '.zip';
  1078. $zip = new ZipArchive();
  1079. if ( true !== $zip->open( $filename, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
  1080. return new WP_Error( 'unable_to_create_zip', __( 'Unable to open export file (archive) for writing.' ) );
  1081. }
  1082. $zip->addEmptyDir( 'templates' );
  1083. $zip->addEmptyDir( 'parts' );
  1084. // Get path of the theme.
  1085. $theme_path = wp_normalize_path( get_stylesheet_directory() );
  1086. // Create recursive directory iterator.
  1087. $theme_files = new RecursiveIteratorIterator(
  1088. new RecursiveDirectoryIterator( $theme_path ),
  1089. RecursiveIteratorIterator::LEAVES_ONLY
  1090. );
  1091. // Make a copy of the current theme.
  1092. foreach ( $theme_files as $file ) {
  1093. // Skip directories as they are added automatically.
  1094. if ( ! $file->isDir() ) {
  1095. // Get real and relative path for current file.
  1096. $file_path = wp_normalize_path( $file );
  1097. $relative_path = substr( $file_path, strlen( $theme_path ) + 1 );
  1098. if ( ! wp_is_theme_directory_ignored( $relative_path ) ) {
  1099. $zip->addFile( $file_path, $relative_path );
  1100. }
  1101. }
  1102. }
  1103. // Load templates into the zip file.
  1104. $templates = get_block_templates();
  1105. foreach ( $templates as $template ) {
  1106. $template->content = _remove_theme_attribute_in_block_template_content( $template->content );
  1107. $zip->addFromString(
  1108. 'templates/' . $template->slug . '.html',
  1109. $template->content
  1110. );
  1111. }
  1112. // Load template parts into the zip file.
  1113. $template_parts = get_block_templates( array(), 'wp_template_part' );
  1114. foreach ( $template_parts as $template_part ) {
  1115. $zip->addFromString(
  1116. 'parts/' . $template_part->slug . '.html',
  1117. $template_part->content
  1118. );
  1119. }
  1120. // Load theme.json into the zip file.
  1121. $tree = WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) );
  1122. // Merge with user data.
  1123. $tree->merge( WP_Theme_JSON_Resolver::get_user_data() );
  1124. $theme_json_raw = $tree->get_data();
  1125. // If a version is defined, add a schema.
  1126. if ( $theme_json_raw['version'] ) {
  1127. global $wp_version;
  1128. $theme_json_version = 'wp/' . substr( $wp_version, 0, 3 );
  1129. $schema = array( '$schema' => 'https://schemas.wp.org/' . $theme_json_version . '/theme.json' );
  1130. $theme_json_raw = array_merge( $schema, $theme_json_raw );
  1131. }
  1132. // Convert to a string.
  1133. $theme_json_encoded = wp_json_encode( $theme_json_raw, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
  1134. // Replace 4 spaces with a tab.
  1135. $theme_json_tabbed = preg_replace( '~(?:^|\G)\h{4}~m', "\t", $theme_json_encoded );
  1136. // Add the theme.json file to the zip.
  1137. $zip->addFromString(
  1138. 'theme.json',
  1139. $theme_json_tabbed
  1140. );
  1141. // Save changes to the zip file.
  1142. $zip->close();
  1143. return $filename;
  1144. }
  1145. /**
  1146. * Gets the template hierarchy for the given template slug to be created.
  1147. *
  1148. *
  1149. * Note: Always add `index` as the last fallback template.
  1150. *
  1151. * @since 6.1.0
  1152. *
  1153. * @param string $slug The template slug to be created.
  1154. * @param boolean $is_custom Optional. Indicates if a template is custom or
  1155. * part of the template hierarchy. Default false.
  1156. * @param string $template_prefix Optional. The template prefix for the created template.
  1157. * Used to extract the main template type, e.g.
  1158. * in `taxonomy-books` the `taxonomy` is extracted.
  1159. * Default empty string.
  1160. * @return string[] The template hierarchy.
  1161. */
  1162. function get_template_hierarchy( $slug, $is_custom = false, $template_prefix = '' ) {
  1163. if ( 'index' === $slug ) {
  1164. return array( 'index' );
  1165. }
  1166. if ( $is_custom ) {
  1167. return array( 'page', 'singular', 'index' );
  1168. }
  1169. if ( 'front-page' === $slug ) {
  1170. return array( 'front-page', 'home', 'index' );
  1171. }
  1172. $template_hierarchy = array( $slug );
  1173. // Most default templates don't have `$template_prefix` assigned.
  1174. if ( $template_prefix ) {
  1175. list( $type ) = explode( '-', $template_prefix );
  1176. // These checks are needed because the `$slug` above is always added.
  1177. if ( ! in_array( $template_prefix, array( $slug, $type ), true ) ) {
  1178. $template_hierarchy[] = $template_prefix;
  1179. }
  1180. if ( $slug !== $type ) {
  1181. $template_hierarchy[] = $type;
  1182. }
  1183. }
  1184. // Handle `archive` template.
  1185. if (
  1186. str_starts_with( $slug, 'author' ) ||
  1187. str_starts_with( $slug, 'taxonomy' ) ||
  1188. str_starts_with( $slug, 'category' ) ||
  1189. str_starts_with( $slug, 'tag' ) ||
  1190. 'date' === $slug
  1191. ) {
  1192. $template_hierarchy[] = 'archive';
  1193. }
  1194. // Handle `single` template.
  1195. if ( 'attachment' === $slug ) {
  1196. $template_hierarchy[] = 'single';
  1197. }
  1198. // Handle `singular` template.
  1199. if (
  1200. str_starts_with( $slug, 'single' ) ||
  1201. str_starts_with( $slug, 'page' ) ||
  1202. 'attachment' === $slug
  1203. ) {
  1204. $template_hierarchy[] = 'singular';
  1205. }
  1206. $template_hierarchy[] = 'index';
  1207. return $template_hierarchy;
  1208. };