Нет описания

block-template-utils.php 32KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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 Post', 'Template name' ),
  126. 'description' => __( 'Displays a single post.' ),
  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 in 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. *
  191. * @return string Input if supported, else the uncategorized value.
  192. */
  193. function _filter_block_template_part_area( $type ) {
  194. $allowed_areas = array_map(
  195. static function ( $item ) {
  196. return $item['area'];
  197. },
  198. get_allowed_block_template_part_areas()
  199. );
  200. if ( in_array( $type, $allowed_areas, true ) ) {
  201. return $type;
  202. }
  203. $warning_message = sprintf(
  204. /* translators: %1$s: Template area type, %2$s: the uncategorized template area value. */
  205. __( '"%1$s" is not a supported wp_template_part area value and has been added as "%2$s".' ),
  206. $type,
  207. WP_TEMPLATE_PART_AREA_UNCATEGORIZED
  208. );
  209. trigger_error( $warning_message, E_USER_NOTICE );
  210. return WP_TEMPLATE_PART_AREA_UNCATEGORIZED;
  211. }
  212. /**
  213. * Finds all nested template part file paths in a theme's directory.
  214. *
  215. * @since 5.9.0
  216. * @access private
  217. *
  218. * @param string $base_directory The theme's file path.
  219. * @return array A list of paths to all template part files.
  220. */
  221. function _get_block_templates_paths( $base_directory ) {
  222. $path_list = array();
  223. if ( file_exists( $base_directory ) ) {
  224. $nested_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base_directory ) );
  225. $nested_html_files = new RegexIterator( $nested_files, '/^.+\.html$/i', RecursiveRegexIterator::GET_MATCH );
  226. foreach ( $nested_html_files as $path => $file ) {
  227. $path_list[] = $path;
  228. }
  229. }
  230. return $path_list;
  231. }
  232. /**
  233. * Retrieves the template file from the theme for a given slug.
  234. *
  235. * @since 5.9.0
  236. * @access private
  237. *
  238. * @param string $template_type 'wp_template' or 'wp_template_part'.
  239. * @param string $slug Template slug.
  240. *
  241. * @return array|null Template.
  242. */
  243. function _get_block_template_file( $template_type, $slug ) {
  244. if ( 'wp_template' !== $template_type && 'wp_template_part' !== $template_type ) {
  245. return null;
  246. }
  247. $themes = array(
  248. get_stylesheet() => get_stylesheet_directory(),
  249. get_template() => get_template_directory(),
  250. );
  251. foreach ( $themes as $theme_slug => $theme_dir ) {
  252. $template_base_paths = get_block_theme_folders( $theme_slug );
  253. $file_path = $theme_dir . '/' . $template_base_paths[ $template_type ] . '/' . $slug . '.html';
  254. if ( file_exists( $file_path ) ) {
  255. $new_template_item = array(
  256. 'slug' => $slug,
  257. 'path' => $file_path,
  258. 'theme' => $theme_slug,
  259. 'type' => $template_type,
  260. );
  261. if ( 'wp_template_part' === $template_type ) {
  262. return _add_block_template_part_area_info( $new_template_item );
  263. }
  264. if ( 'wp_template' === $template_type ) {
  265. return _add_block_template_info( $new_template_item );
  266. }
  267. return $new_template_item;
  268. }
  269. }
  270. return null;
  271. }
  272. /**
  273. * Retrieves the template files from the theme.
  274. *
  275. * @since 5.9.0
  276. * @access private
  277. *
  278. * @param string $template_type 'wp_template' or 'wp_template_part'.
  279. *
  280. * @return array Template.
  281. */
  282. function _get_block_templates_files( $template_type ) {
  283. if ( 'wp_template' !== $template_type && 'wp_template_part' !== $template_type ) {
  284. return null;
  285. }
  286. $themes = array(
  287. get_stylesheet() => get_stylesheet_directory(),
  288. get_template() => get_template_directory(),
  289. );
  290. $template_files = array();
  291. foreach ( $themes as $theme_slug => $theme_dir ) {
  292. $template_base_paths = get_block_theme_folders( $theme_slug );
  293. $theme_template_files = _get_block_templates_paths( $theme_dir . '/' . $template_base_paths[ $template_type ] );
  294. foreach ( $theme_template_files as $template_file ) {
  295. $template_base_path = $template_base_paths[ $template_type ];
  296. $template_slug = substr(
  297. $template_file,
  298. // Starting position of slug.
  299. strpos( $template_file, $template_base_path . DIRECTORY_SEPARATOR ) + 1 + strlen( $template_base_path ),
  300. // Subtract ending '.html'.
  301. -5
  302. );
  303. $new_template_item = array(
  304. 'slug' => $template_slug,
  305. 'path' => $template_file,
  306. 'theme' => $theme_slug,
  307. 'type' => $template_type,
  308. );
  309. if ( 'wp_template_part' === $template_type ) {
  310. $template_files[] = _add_block_template_part_area_info( $new_template_item );
  311. }
  312. if ( 'wp_template' === $template_type ) {
  313. $template_files[] = _add_block_template_info( $new_template_item );
  314. }
  315. }
  316. }
  317. return $template_files;
  318. }
  319. /**
  320. * Attempts to add custom template information to the template item.
  321. *
  322. * @since 5.9.0
  323. * @access private
  324. *
  325. * @param array $template_item Template to add information to (requires 'slug' field).
  326. * @return array Template item.
  327. */
  328. function _add_block_template_info( $template_item ) {
  329. if ( ! WP_Theme_JSON_Resolver::theme_has_support() ) {
  330. return $template_item;
  331. }
  332. $theme_data = WP_Theme_JSON_Resolver::get_theme_data()->get_custom_templates();
  333. if ( isset( $theme_data[ $template_item['slug'] ] ) ) {
  334. $template_item['title'] = $theme_data[ $template_item['slug'] ]['title'];
  335. $template_item['postTypes'] = $theme_data[ $template_item['slug'] ]['postTypes'];
  336. }
  337. return $template_item;
  338. }
  339. /**
  340. * Attempts to add the template part's area information to the input template.
  341. *
  342. * @since 5.9.0
  343. * @access private
  344. *
  345. * @param array $template_info Template to add information to (requires 'type' and 'slug' fields).
  346. *
  347. * @return array Template info.
  348. */
  349. function _add_block_template_part_area_info( $template_info ) {
  350. if ( WP_Theme_JSON_Resolver::theme_has_support() ) {
  351. $theme_data = WP_Theme_JSON_Resolver::get_theme_data()->get_template_parts();
  352. }
  353. if ( isset( $theme_data[ $template_info['slug'] ]['area'] ) ) {
  354. $template_info['title'] = $theme_data[ $template_info['slug'] ]['title'];
  355. $template_info['area'] = _filter_block_template_part_area( $theme_data[ $template_info['slug'] ]['area'] );
  356. } else {
  357. $template_info['area'] = WP_TEMPLATE_PART_AREA_UNCATEGORIZED;
  358. }
  359. return $template_info;
  360. }
  361. /**
  362. * Returns an array containing the references of
  363. * the passed blocks and their inner blocks.
  364. *
  365. * @since 5.9.0
  366. * @access private
  367. *
  368. * @param array $blocks array of blocks.
  369. *
  370. * @return array block references to the passed blocks and their inner blocks.
  371. */
  372. function _flatten_blocks( &$blocks ) {
  373. $all_blocks = array();
  374. $queue = array();
  375. foreach ( $blocks as &$block ) {
  376. $queue[] = &$block;
  377. }
  378. while ( count( $queue ) > 0 ) {
  379. $block = &$queue[0];
  380. array_shift( $queue );
  381. $all_blocks[] = &$block;
  382. if ( ! empty( $block['innerBlocks'] ) ) {
  383. foreach ( $block['innerBlocks'] as &$inner_block ) {
  384. $queue[] = &$inner_block;
  385. }
  386. }
  387. }
  388. return $all_blocks;
  389. }
  390. /**
  391. * Parses wp_template content and injects the active theme's
  392. * stylesheet as a theme attribute into each wp_template_part
  393. *
  394. * @since 5.9.0
  395. * @access private
  396. *
  397. * @param string $template_content serialized wp_template content.
  398. *
  399. * @return string Updated 'wp_template' content.
  400. */
  401. function _inject_theme_attribute_in_block_template_content( $template_content ) {
  402. $has_updated_content = false;
  403. $new_content = '';
  404. $template_blocks = parse_blocks( $template_content );
  405. $blocks = _flatten_blocks( $template_blocks );
  406. foreach ( $blocks as &$block ) {
  407. if (
  408. 'core/template-part' === $block['blockName'] &&
  409. ! isset( $block['attrs']['theme'] )
  410. ) {
  411. $block['attrs']['theme'] = wp_get_theme()->get_stylesheet();
  412. $has_updated_content = true;
  413. }
  414. }
  415. if ( $has_updated_content ) {
  416. foreach ( $template_blocks as &$block ) {
  417. $new_content .= serialize_block( $block );
  418. }
  419. return $new_content;
  420. }
  421. return $template_content;
  422. }
  423. /**
  424. * Parses a block template and removes the theme attribute from each template part.
  425. *
  426. * @since 5.9.0
  427. * @access private
  428. *
  429. * @param string $template_content Serialized block template content.
  430. * @return string Updated block template content.
  431. */
  432. function _remove_theme_attribute_in_block_template_content( $template_content ) {
  433. $has_updated_content = false;
  434. $new_content = '';
  435. $template_blocks = parse_blocks( $template_content );
  436. $blocks = _flatten_blocks( $template_blocks );
  437. foreach ( $blocks as $key => $block ) {
  438. if ( 'core/template-part' === $block['blockName'] && isset( $block['attrs']['theme'] ) ) {
  439. unset( $blocks[ $key ]['attrs']['theme'] );
  440. $has_updated_content = true;
  441. }
  442. }
  443. if ( ! $has_updated_content ) {
  444. return $template_content;
  445. }
  446. foreach ( $template_blocks as $block ) {
  447. $new_content .= serialize_block( $block );
  448. }
  449. return $new_content;
  450. }
  451. /**
  452. * Build a unified template object based on a theme file.
  453. *
  454. * @since 5.9.0
  455. * @access private
  456. *
  457. * @param array $template_file Theme file.
  458. * @param string $template_type 'wp_template' or 'wp_template_part'.
  459. *
  460. * @return WP_Block_Template Template.
  461. */
  462. function _build_block_template_result_from_file( $template_file, $template_type ) {
  463. $default_template_types = get_default_block_template_types();
  464. $template_content = file_get_contents( $template_file['path'] );
  465. $theme = wp_get_theme()->get_stylesheet();
  466. $template = new WP_Block_Template();
  467. $template->id = $theme . '//' . $template_file['slug'];
  468. $template->theme = $theme;
  469. $template->content = _inject_theme_attribute_in_block_template_content( $template_content );
  470. $template->slug = $template_file['slug'];
  471. $template->source = 'theme';
  472. $template->type = $template_type;
  473. $template->title = ! empty( $template_file['title'] ) ? $template_file['title'] : $template_file['slug'];
  474. $template->status = 'publish';
  475. $template->has_theme_file = true;
  476. $template->is_custom = true;
  477. if ( 'wp_template' === $template_type && isset( $default_template_types[ $template_file['slug'] ] ) ) {
  478. $template->description = $default_template_types[ $template_file['slug'] ]['description'];
  479. $template->title = $default_template_types[ $template_file['slug'] ]['title'];
  480. $template->is_custom = false;
  481. }
  482. if ( 'wp_template' === $template_type && isset( $template_file['postTypes'] ) ) {
  483. $template->post_types = $template_file['postTypes'];
  484. }
  485. if ( 'wp_template_part' === $template_type && isset( $template_file['area'] ) ) {
  486. $template->area = $template_file['area'];
  487. }
  488. return $template;
  489. }
  490. /**
  491. * Build a unified template object based a post Object.
  492. *
  493. * @since 5.9.0
  494. * @access private
  495. *
  496. * @param WP_Post $post Template post.
  497. *
  498. * @return WP_Block_Template|WP_Error Template.
  499. */
  500. function _build_block_template_result_from_post( $post ) {
  501. $default_template_types = get_default_block_template_types();
  502. $terms = get_the_terms( $post, 'wp_theme' );
  503. if ( is_wp_error( $terms ) ) {
  504. return $terms;
  505. }
  506. if ( ! $terms ) {
  507. return new WP_Error( 'template_missing_theme', __( 'No theme is defined for this template.' ) );
  508. }
  509. $theme = $terms[0]->name;
  510. $has_theme_file = wp_get_theme()->get_stylesheet() === $theme &&
  511. null !== _get_block_template_file( $post->post_type, $post->post_name );
  512. $origin = get_post_meta( $post->ID, 'origin', true );
  513. $template = new WP_Block_Template();
  514. $template->wp_id = $post->ID;
  515. $template->id = $theme . '//' . $post->post_name;
  516. $template->theme = $theme;
  517. $template->content = $post->post_content;
  518. $template->slug = $post->post_name;
  519. $template->source = 'custom';
  520. $template->origin = ! empty( $origin ) ? $origin : null;
  521. $template->type = $post->post_type;
  522. $template->description = $post->post_excerpt;
  523. $template->title = $post->post_title;
  524. $template->status = $post->post_status;
  525. $template->has_theme_file = $has_theme_file;
  526. $template->is_custom = true;
  527. $template->author = $post->post_author;
  528. if ( 'wp_template' === $post->post_type && isset( $default_template_types[ $template->slug ] ) ) {
  529. $template->is_custom = false;
  530. }
  531. if ( 'wp_template_part' === $post->post_type ) {
  532. $type_terms = get_the_terms( $post, 'wp_template_part_area' );
  533. if ( ! is_wp_error( $type_terms ) && false !== $type_terms ) {
  534. $template->area = $type_terms[0]->name;
  535. }
  536. }
  537. return $template;
  538. }
  539. /**
  540. * Retrieves a list of unified template objects based on a query.
  541. *
  542. * @since 5.8.0
  543. *
  544. * @param array $query {
  545. * Optional. Arguments to retrieve templates.
  546. *
  547. * @type array $slug__in List of slugs to include.
  548. * @type int $wp_id Post ID of customized template.
  549. * @type string $area A 'wp_template_part_area' taxonomy value to filter by (for wp_template_part template type only).
  550. * @type string $post_type Post type to get the templates for.
  551. * }
  552. * @param string $template_type 'wp_template' or 'wp_template_part'.
  553. *
  554. * @return array Templates.
  555. */
  556. function get_block_templates( $query = array(), $template_type = 'wp_template' ) {
  557. /**
  558. * Filters the block templates array before the query takes place.
  559. *
  560. * Return a non-null value to bypass the WordPress queries.
  561. *
  562. * @since 5.9.0
  563. *
  564. * @param WP_Block_Template[]|null $block_templates Return an array of block templates to short-circuit the default query,
  565. * or null to allow WP to run it's normal queries.
  566. * @param array $query {
  567. * Optional. Arguments to retrieve templates.
  568. *
  569. * @type array $slug__in List of slugs to include.
  570. * @type int $wp_id Post ID of customized template.
  571. * @type string $post_type Post type to get the templates for.
  572. * }
  573. * @param string $template_type wp_template or wp_template_part.
  574. */
  575. $templates = apply_filters( 'pre_get_block_templates', null, $query, $template_type );
  576. if ( ! is_null( $templates ) ) {
  577. return $templates;
  578. }
  579. $post_type = isset( $query['post_type'] ) ? $query['post_type'] : '';
  580. $wp_query_args = array(
  581. 'post_status' => array( 'auto-draft', 'draft', 'publish' ),
  582. 'post_type' => $template_type,
  583. 'posts_per_page' => -1,
  584. 'no_found_rows' => true,
  585. 'tax_query' => array(
  586. array(
  587. 'taxonomy' => 'wp_theme',
  588. 'field' => 'name',
  589. 'terms' => wp_get_theme()->get_stylesheet(),
  590. ),
  591. ),
  592. );
  593. if ( 'wp_template_part' === $template_type && isset( $query['area'] ) ) {
  594. $wp_query_args['tax_query'][] = array(
  595. 'taxonomy' => 'wp_template_part_area',
  596. 'field' => 'name',
  597. 'terms' => $query['area'],
  598. );
  599. $wp_query_args['tax_query']['relation'] = 'AND';
  600. }
  601. if ( isset( $query['slug__in'] ) ) {
  602. $wp_query_args['post_name__in'] = $query['slug__in'];
  603. }
  604. // This is only needed for the regular templates/template parts post type listing and editor.
  605. if ( isset( $query['wp_id'] ) ) {
  606. $wp_query_args['p'] = $query['wp_id'];
  607. } else {
  608. $wp_query_args['post_status'] = 'publish';
  609. }
  610. $template_query = new WP_Query( $wp_query_args );
  611. $query_result = array();
  612. foreach ( $template_query->posts as $post ) {
  613. $template = _build_block_template_result_from_post( $post );
  614. if ( is_wp_error( $template ) ) {
  615. continue;
  616. }
  617. if ( $post_type && ! $template->is_custom ) {
  618. continue;
  619. }
  620. $query_result[] = $template;
  621. }
  622. if ( ! isset( $query['wp_id'] ) ) {
  623. $template_files = _get_block_templates_files( $template_type );
  624. foreach ( $template_files as $template_file ) {
  625. $template = _build_block_template_result_from_file( $template_file, $template_type );
  626. if ( $post_type && ! $template->is_custom ) {
  627. continue;
  628. }
  629. if ( $post_type &&
  630. isset( $template->post_types ) &&
  631. ! in_array( $post_type, $template->post_types, true )
  632. ) {
  633. continue;
  634. }
  635. $is_not_custom = false === array_search(
  636. wp_get_theme()->get_stylesheet() . '//' . $template_file['slug'],
  637. array_column( $query_result, 'id' ),
  638. true
  639. );
  640. $fits_slug_query =
  641. ! isset( $query['slug__in'] ) || in_array( $template_file['slug'], $query['slug__in'], true );
  642. $fits_area_query =
  643. ! isset( $query['area'] ) || $template_file['area'] === $query['area'];
  644. $should_include = $is_not_custom && $fits_slug_query && $fits_area_query;
  645. if ( $should_include ) {
  646. $query_result[] = $template;
  647. }
  648. }
  649. }
  650. /**
  651. * Filters the array of queried block templates array after they've been fetched.
  652. *
  653. * @since 5.9.0
  654. *
  655. * @param WP_Block_Template[] $query_result Array of found block templates.
  656. * @param array $query {
  657. * Optional. Arguments to retrieve templates.
  658. *
  659. * @type array $slug__in List of slugs to include.
  660. * @type int $wp_id Post ID of customized template.
  661. * }
  662. * @param string $template_type wp_template or wp_template_part.
  663. */
  664. return apply_filters( 'get_block_templates', $query_result, $query, $template_type );
  665. }
  666. /**
  667. * Retrieves a single unified template object using its id.
  668. *
  669. * @since 5.8.0
  670. *
  671. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  672. * @param string $template_type Optional. Template type: `'wp_template'` or '`wp_template_part'`.
  673. * Default `'wp_template'`.
  674. *
  675. * @return WP_Block_Template|null Template.
  676. */
  677. function get_block_template( $id, $template_type = 'wp_template' ) {
  678. /**
  679. *Filters the block template object before the query takes place.
  680. *
  681. * Return a non-null value to bypass the WordPress queries.
  682. *
  683. * @since 5.9.0
  684. *
  685. * @param WP_Block_Template|null $block_template Return block template object to short-circuit the default query,
  686. * or null to allow WP to run its normal queries.
  687. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  688. * @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  689. */
  690. $block_template = apply_filters( 'pre_get_block_template', null, $id, $template_type );
  691. if ( ! is_null( $block_template ) ) {
  692. return $block_template;
  693. }
  694. $parts = explode( '//', $id, 2 );
  695. if ( count( $parts ) < 2 ) {
  696. return null;
  697. }
  698. list( $theme, $slug ) = $parts;
  699. $wp_query_args = array(
  700. 'post_name__in' => array( $slug ),
  701. 'post_type' => $template_type,
  702. 'post_status' => array( 'auto-draft', 'draft', 'publish', 'trash' ),
  703. 'posts_per_page' => 1,
  704. 'no_found_rows' => true,
  705. 'tax_query' => array(
  706. array(
  707. 'taxonomy' => 'wp_theme',
  708. 'field' => 'name',
  709. 'terms' => $theme,
  710. ),
  711. ),
  712. );
  713. $template_query = new WP_Query( $wp_query_args );
  714. $posts = $template_query->posts;
  715. if ( count( $posts ) > 0 ) {
  716. $template = _build_block_template_result_from_post( $posts[0] );
  717. if ( ! is_wp_error( $template ) ) {
  718. return $template;
  719. }
  720. }
  721. $block_template = get_block_file_template( $id, $template_type );
  722. /**
  723. * Filters the queried block template object after it's been fetched.
  724. *
  725. * @since 5.9.0
  726. *
  727. * @param WP_Block_Template|null $block_template The found block template, or null if there isn't one.
  728. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  729. * @param array $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  730. */
  731. return apply_filters( 'get_block_template', $block_template, $id, $template_type );
  732. }
  733. /**
  734. * Retrieves a single unified template object using its id.
  735. *
  736. * @since 5.9.0
  737. *
  738. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  739. * @param string $template_type Optional. Template type: `'wp_template'` or '`wp_template_part'`.
  740. * Default `'wp_template'`.
  741. * @return WP_Block_Template|null The found block template, or null if there isn't one.
  742. */
  743. function get_block_file_template( $id, $template_type = 'wp_template' ) {
  744. /**
  745. * Filters the block templates array before the query takes place.
  746. *
  747. * Return a non-null value to bypass the WordPress queries.
  748. *
  749. * @since 5.9.0
  750. *
  751. * @param WP_Block_Template|null $block_template Return block template object to short-circuit the default query,
  752. * or null to allow WP to run its normal queries.
  753. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  754. * @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  755. */
  756. $block_template = apply_filters( 'pre_get_block_file_template', null, $id, $template_type );
  757. if ( ! is_null( $block_template ) ) {
  758. return $block_template;
  759. }
  760. $parts = explode( '//', $id, 2 );
  761. if ( count( $parts ) < 2 ) {
  762. /** This filter is documented in wp-includes/block-template-utils.php */
  763. return apply_filters( 'get_block_file_template', null, $id, $template_type );
  764. }
  765. list( $theme, $slug ) = $parts;
  766. if ( wp_get_theme()->get_stylesheet() !== $theme ) {
  767. /** This filter is documented in wp-includes/block-template-utils.php */
  768. return apply_filters( 'get_block_file_template', null, $id, $template_type );
  769. }
  770. $template_file = _get_block_template_file( $template_type, $slug );
  771. if ( null === $template_file ) {
  772. /** This filter is documented in wp-includes/block-template-utils.php */
  773. return apply_filters( 'get_block_file_template', null, $id, $template_type );
  774. }
  775. $block_template = _build_block_template_result_from_file( $template_file, $template_type );
  776. /**
  777. * Filters the array of queried block templates array after they've been fetched.
  778. *
  779. * @since 5.9.0
  780. *
  781. * @param WP_Block_Template|null $block_template The found block template, or null if there is none.
  782. * @param string $id Template unique identifier (example: theme_slug//template_slug).
  783. * @param string $template_type Template type: `'wp_template'` or '`wp_template_part'`.
  784. */
  785. return apply_filters( 'get_block_file_template', $block_template, $id, $template_type );
  786. }
  787. /**
  788. * Print a template-part.
  789. *
  790. * @since 5.9.0
  791. *
  792. * @param string $part The template-part to print. Use "header" or "footer".
  793. */
  794. function block_template_part( $part ) {
  795. $template_part = get_block_template( get_stylesheet() . '//' . $part, 'wp_template_part' );
  796. if ( ! $template_part || empty( $template_part->content ) ) {
  797. return;
  798. }
  799. echo do_blocks( $template_part->content );
  800. }
  801. /**
  802. * Print the header template-part.
  803. *
  804. * @since 5.9.0
  805. */
  806. function block_header_area() {
  807. block_template_part( 'header' );
  808. }
  809. /**
  810. * Print the footer template-part.
  811. *
  812. * @since 5.9.0
  813. */
  814. function block_footer_area() {
  815. block_template_part( 'footer' );
  816. }
  817. /**
  818. * Filters theme directories that should be ignored during export.
  819. *
  820. * @since 6.0.0
  821. *
  822. * @param string $path The path of the file in the theme.
  823. * @return Bool Whether this file is in an ignored directory.
  824. */
  825. function wp_is_theme_directory_ignored( $path ) {
  826. $directories_to_ignore = array( '.svn', '.git', '.hg', '.bzr', 'node_modules', 'vendor' );
  827. foreach ( $directories_to_ignore as $directory ) {
  828. if ( strpos( $path, $directory ) === 0 ) {
  829. return true;
  830. }
  831. }
  832. return false;
  833. }
  834. /**
  835. * Creates an export of the current templates and
  836. * template parts from the site editor at the
  837. * specified path in a ZIP file.
  838. *
  839. * @since 5.9.0
  840. * @since 6.0.0 Adds the whole theme to the export archive.
  841. *
  842. * @return WP_Error|string Path of the ZIP file or error on failure.
  843. */
  844. function wp_generate_block_templates_export_file() {
  845. if ( ! class_exists( 'ZipArchive' ) ) {
  846. return new WP_Error( 'missing_zip_package', __( 'Zip Export not supported.' ) );
  847. }
  848. $obscura = wp_generate_password( 12, false, false );
  849. $theme_name = basename( get_stylesheet() );
  850. $filename = get_temp_dir() . $theme_name . $obscura . '.zip';
  851. $zip = new ZipArchive();
  852. if ( true !== $zip->open( $filename, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
  853. return new WP_Error( 'unable_to_create_zip', __( 'Unable to open export file (archive) for writing.' ) );
  854. }
  855. $zip->addEmptyDir( 'templates' );
  856. $zip->addEmptyDir( 'parts' );
  857. // Get path of the theme.
  858. $theme_path = wp_normalize_path( get_stylesheet_directory() );
  859. // Create recursive directory iterator.
  860. $theme_files = new RecursiveIteratorIterator(
  861. new RecursiveDirectoryIterator( $theme_path ),
  862. RecursiveIteratorIterator::LEAVES_ONLY
  863. );
  864. // Make a copy of the current theme.
  865. foreach ( $theme_files as $file ) {
  866. // Skip directories as they are added automatically.
  867. if ( ! $file->isDir() ) {
  868. // Get real and relative path for current file.
  869. $file_path = wp_normalize_path( $file );
  870. $relative_path = substr( $file_path, strlen( $theme_path ) + 1 );
  871. if ( ! wp_is_theme_directory_ignored( $relative_path ) ) {
  872. $zip->addFile( $file_path, $relative_path );
  873. }
  874. }
  875. }
  876. // Load templates into the zip file.
  877. $templates = get_block_templates();
  878. foreach ( $templates as $template ) {
  879. $template->content = _remove_theme_attribute_in_block_template_content( $template->content );
  880. $zip->addFromString(
  881. 'templates/' . $template->slug . '.html',
  882. $template->content
  883. );
  884. }
  885. // Load template parts into the zip file.
  886. $template_parts = get_block_templates( array(), 'wp_template_part' );
  887. foreach ( $template_parts as $template_part ) {
  888. $zip->addFromString(
  889. 'parts/' . $template_part->slug . '.html',
  890. $template_part->content
  891. );
  892. }
  893. // Load theme.json into the zip file.
  894. $tree = WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) );
  895. // Merge with user data.
  896. $tree->merge( WP_Theme_JSON_Resolver::get_user_data() );
  897. $theme_json_raw = $tree->get_data();
  898. // If a version is defined, add a schema.
  899. if ( $theme_json_raw['version'] ) {
  900. global $wp_version;
  901. $theme_json_version = 'wp/' . substr( $wp_version, 0, 3 );
  902. $schema = array( '$schema' => 'https://schemas.wp.org/' . $theme_json_version . '/theme.json' );
  903. $theme_json_raw = array_merge( $schema, $theme_json_raw );
  904. }
  905. // Convert to a string.
  906. $theme_json_encoded = wp_json_encode( $theme_json_raw, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
  907. // Replace 4 spaces with a tab.
  908. $theme_json_tabbed = preg_replace( '~(?:^|\G)\h{4}~m', "\t", $theme_json_encoded );
  909. // Add the theme.json file to the zip.
  910. $zip->addFromString(
  911. 'theme.json',
  912. $theme_json_tabbed
  913. );
  914. // Save changes to the zip file.
  915. $zip->close();
  916. return $filename;
  917. }