block-template.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. <?php
  2. /**
  3. * Block template loader functions.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Adds necessary filters to use 'wp_template' posts instead of theme template files.
  9. *
  10. * @access private
  11. * @since 5.9.0
  12. */
  13. function _add_template_loader_filters() {
  14. if ( ! current_theme_supports( 'block-templates' ) ) {
  15. return;
  16. }
  17. $template_types = array_keys( get_default_block_template_types() );
  18. foreach ( $template_types as $template_type ) {
  19. // Skip 'embed' for now because it is not a regular template type.
  20. if ( 'embed' === $template_type ) {
  21. continue;
  22. }
  23. add_filter( str_replace( '-', '', $template_type ) . '_template', 'locate_block_template', 20, 3 );
  24. }
  25. // Request to resolve a template.
  26. if ( isset( $_GET['_wp-find-template'] ) ) {
  27. add_filter( 'pre_get_posts', '_resolve_template_for_new_post' );
  28. }
  29. }
  30. /**
  31. * Finds a block template with equal or higher specificity than a given PHP template file.
  32. *
  33. * Internally, this communicates the block content that needs to be used by the template canvas through a global variable.
  34. *
  35. * @since 5.8.0
  36. *
  37. * @global string $_wp_current_template_content
  38. *
  39. * @param string $template Path to the template. See locate_template().
  40. * @param string $type Sanitized filename without extension.
  41. * @param string[] $templates A list of template candidates, in descending order of priority.
  42. * @return string The path to the Site Editor template canvas file, or the fallback PHP template.
  43. */
  44. function locate_block_template( $template, $type, array $templates ) {
  45. global $_wp_current_template_content;
  46. if ( ! current_theme_supports( 'block-templates' ) ) {
  47. return $template;
  48. }
  49. if ( $template ) {
  50. /*
  51. * locate_template() has found a PHP template at the path specified by $template.
  52. * That means that we have a fallback candidate if we cannot find a block template
  53. * with higher specificity.
  54. *
  55. * Thus, before looking for matching block themes, we shorten our list of candidate
  56. * templates accordingly.
  57. */
  58. // Locate the index of $template (without the theme directory path) in $templates.
  59. $relative_template_path = str_replace(
  60. array( get_stylesheet_directory() . '/', get_template_directory() . '/' ),
  61. '',
  62. $template
  63. );
  64. $index = array_search( $relative_template_path, $templates, true );
  65. // If the template hierarchy algorithm has successfully located a PHP template file,
  66. // we will only consider block templates with higher or equal specificity.
  67. $templates = array_slice( $templates, 0, $index + 1 );
  68. }
  69. $block_template = resolve_block_template( $type, $templates, $template );
  70. if ( $block_template ) {
  71. if ( empty( $block_template->content ) && is_user_logged_in() ) {
  72. $_wp_current_template_content =
  73. sprintf(
  74. /* translators: %s: Template title */
  75. __( 'Empty template: %s' ),
  76. $block_template->title
  77. );
  78. } elseif ( ! empty( $block_template->content ) ) {
  79. $_wp_current_template_content = $block_template->content;
  80. }
  81. if ( isset( $_GET['_wp-find-template'] ) ) {
  82. wp_send_json_success( $block_template );
  83. }
  84. } else {
  85. if ( $template ) {
  86. return $template;
  87. }
  88. if ( 'index' === $type ) {
  89. if ( isset( $_GET['_wp-find-template'] ) ) {
  90. wp_send_json_error( array( 'message' => __( 'No matching template found.' ) ) );
  91. }
  92. } else {
  93. return ''; // So that the template loader keeps looking for templates.
  94. }
  95. }
  96. // Add hooks for template canvas.
  97. // Add viewport meta tag.
  98. add_action( 'wp_head', '_block_template_viewport_meta_tag', 0 );
  99. // Render title tag with content, regardless of whether theme has title-tag support.
  100. remove_action( 'wp_head', '_wp_render_title_tag', 1 ); // Remove conditional title tag rendering...
  101. add_action( 'wp_head', '_block_template_render_title_tag', 1 ); // ...and make it unconditional.
  102. // This file will be included instead of the theme's template file.
  103. return ABSPATH . WPINC . '/template-canvas.php';
  104. }
  105. /**
  106. * Returns the correct 'wp_template' to render for the request template type.
  107. *
  108. * @access private
  109. * @since 5.8.0
  110. * @since 5.9.0 Added the `$fallback_template` parameter.
  111. *
  112. * @param string $template_type The current template type.
  113. * @param string[] $template_hierarchy The current template hierarchy, ordered by priority.
  114. * @param string $fallback_template A PHP fallback template to use if no matching block template is found.
  115. * @return WP_Block_Template|null template A template object, or null if none could be found.
  116. */
  117. function resolve_block_template( $template_type, $template_hierarchy, $fallback_template ) {
  118. if ( ! $template_type ) {
  119. return null;
  120. }
  121. if ( empty( $template_hierarchy ) ) {
  122. $template_hierarchy = array( $template_type );
  123. }
  124. $slugs = array_map(
  125. '_strip_template_file_suffix',
  126. $template_hierarchy
  127. );
  128. // Find all potential templates 'wp_template' post matching the hierarchy.
  129. $query = array(
  130. 'theme' => get_stylesheet(),
  131. 'slug__in' => $slugs,
  132. );
  133. $templates = get_block_templates( $query );
  134. // Order these templates per slug priority.
  135. // Build map of template slugs to their priority in the current hierarchy.
  136. $slug_priorities = array_flip( $slugs );
  137. usort(
  138. $templates,
  139. static function ( $template_a, $template_b ) use ( $slug_priorities ) {
  140. return $slug_priorities[ $template_a->slug ] - $slug_priorities[ $template_b->slug ];
  141. }
  142. );
  143. $theme_base_path = get_stylesheet_directory() . DIRECTORY_SEPARATOR;
  144. $parent_theme_base_path = get_template_directory() . DIRECTORY_SEPARATOR;
  145. // Is the active theme a child theme, and is the PHP fallback template part of it?
  146. if (
  147. strpos( $fallback_template, $theme_base_path ) === 0 &&
  148. strpos( $fallback_template, $parent_theme_base_path ) === false
  149. ) {
  150. $fallback_template_slug = substr(
  151. $fallback_template,
  152. // Starting position of slug.
  153. strpos( $fallback_template, $theme_base_path ) + strlen( $theme_base_path ),
  154. // Remove '.php' suffix.
  155. -4
  156. );
  157. // Is our candidate block template's slug identical to our PHP fallback template's?
  158. if (
  159. count( $templates ) &&
  160. $fallback_template_slug === $templates[0]->slug &&
  161. 'theme' === $templates[0]->source
  162. ) {
  163. // Unfortunately, we cannot trust $templates[0]->theme, since it will always
  164. // be set to the active theme's slug by _build_block_template_result_from_file(),
  165. // even if the block template is really coming from the active theme's parent.
  166. // (The reason for this is that we want it to be associated with the active theme
  167. // -- not its parent -- once we edit it and store it to the DB as a wp_template CPT.)
  168. // Instead, we use _get_block_template_file() to locate the block template file.
  169. $template_file = _get_block_template_file( 'wp_template', $fallback_template_slug );
  170. if ( $template_file && get_template() === $template_file['theme'] ) {
  171. // The block template is part of the parent theme, so we
  172. // have to give precedence to the child theme's PHP template.
  173. array_shift( $templates );
  174. }
  175. }
  176. }
  177. return count( $templates ) ? $templates[0] : null;
  178. }
  179. /**
  180. * Displays title tag with content, regardless of whether theme has title-tag support.
  181. *
  182. * @access private
  183. * @since 5.8.0
  184. *
  185. * @see _wp_render_title_tag()
  186. */
  187. function _block_template_render_title_tag() {
  188. echo '<title>' . wp_get_document_title() . '</title>' . "\n";
  189. }
  190. /**
  191. * Returns the markup for the current template.
  192. *
  193. * @access private
  194. * @since 5.8.0
  195. *
  196. * @global string $_wp_current_template_content
  197. * @global WP_Embed $wp_embed
  198. *
  199. * @return string Block template markup.
  200. */
  201. function get_the_block_template_html() {
  202. global $_wp_current_template_content;
  203. global $wp_embed;
  204. if ( ! $_wp_current_template_content ) {
  205. if ( is_user_logged_in() ) {
  206. return '<h1>' . esc_html__( 'No matching template found' ) . '</h1>';
  207. }
  208. return;
  209. }
  210. $content = $wp_embed->run_shortcode( $_wp_current_template_content );
  211. $content = $wp_embed->autoembed( $content );
  212. $content = do_blocks( $content );
  213. $content = wptexturize( $content );
  214. $content = convert_smilies( $content );
  215. $content = shortcode_unautop( $content );
  216. $content = wp_filter_content_tags( $content );
  217. $content = do_shortcode( $content );
  218. $content = str_replace( ']]>', ']]&gt;', $content );
  219. // Wrap block template in .wp-site-blocks to allow for specific descendant styles
  220. // (e.g. `.wp-site-blocks > *`).
  221. return '<div class="wp-site-blocks">' . $content . '</div>';
  222. }
  223. /**
  224. * Renders a 'viewport' meta tag.
  225. *
  226. * This is hooked into {@see 'wp_head'} to decouple its output from the default template canvas.
  227. *
  228. * @access private
  229. * @since 5.8.0
  230. */
  231. function _block_template_viewport_meta_tag() {
  232. echo '<meta name="viewport" content="width=device-width, initial-scale=1" />' . "\n";
  233. }
  234. /**
  235. * Strips .php or .html suffix from template file names.
  236. *
  237. * @access private
  238. * @since 5.8.0
  239. *
  240. * @param string $template_file Template file name.
  241. * @return string Template file name without extension.
  242. */
  243. function _strip_template_file_suffix( $template_file ) {
  244. return preg_replace( '/\.(php|html)$/', '', $template_file );
  245. }
  246. /**
  247. * Removes post details from block context when rendering a block template.
  248. *
  249. * @access private
  250. * @since 5.8.0
  251. *
  252. * @param array $context Default context.
  253. *
  254. * @return array Filtered context.
  255. */
  256. function _block_template_render_without_post_block_context( $context ) {
  257. /*
  258. * When loading a template directly and not through a page that resolves it,
  259. * the top-level post ID and type context get set to that of the template.
  260. * Templates are just the structure of a site, and they should not be available
  261. * as post context because blocks like Post Content would recurse infinitely.
  262. */
  263. if ( isset( $context['postType'] ) && 'wp_template' === $context['postType'] ) {
  264. unset( $context['postId'] );
  265. unset( $context['postType'] );
  266. }
  267. return $context;
  268. }
  269. /**
  270. * Sets the current WP_Query to return auto-draft posts.
  271. *
  272. * The auto-draft status indicates a new post, so allow the the WP_Query instance to
  273. * return an auto-draft post for template resolution when editing a new post.
  274. *
  275. * @access private
  276. * @since 5.9.0
  277. *
  278. * @param WP_Query $wp_query Current WP_Query instance, passed by reference.
  279. */
  280. function _resolve_template_for_new_post( $wp_query ) {
  281. if ( ! $wp_query->is_main_query() ) {
  282. return;
  283. }
  284. remove_filter( 'pre_get_posts', '_resolve_template_for_new_post' );
  285. // Pages.
  286. $page_id = isset( $wp_query->query['page_id'] ) ? $wp_query->query['page_id'] : null;
  287. // Posts, including custom post types.
  288. $p = isset( $wp_query->query['p'] ) ? $wp_query->query['p'] : null;
  289. $post_id = $page_id ? $page_id : $p;
  290. $post = get_post( $post_id );
  291. if (
  292. $post &&
  293. 'auto-draft' === $post->post_status &&
  294. current_user_can( 'edit_post', $post->ID )
  295. ) {
  296. $wp_query->set( 'post_status', 'auto-draft' );
  297. }
  298. }
  299. /**
  300. * Returns the correct template for the site's home page.
  301. *
  302. * @access private
  303. * @since 6.0.0
  304. *
  305. * @return array|null A template object, or null if none could be found.
  306. */
  307. function _resolve_home_block_template() {
  308. $show_on_front = get_option( 'show_on_front' );
  309. $front_page_id = get_option( 'page_on_front' );
  310. if ( 'page' === $show_on_front && $front_page_id ) {
  311. return array(
  312. 'postType' => 'page',
  313. 'postId' => $front_page_id,
  314. );
  315. }
  316. $hierarchy = array( 'front-page', 'home', 'index' );
  317. $template = resolve_block_template( 'home', $hierarchy, '' );
  318. if ( ! $template ) {
  319. return null;
  320. }
  321. return array(
  322. 'postType' => 'wp_template',
  323. 'postId' => $template->id,
  324. );
  325. }