PluginProbe
Gutenberg / 8.3.0
Gutenberg v8.3.0
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / lib / template-loader.php

template-loader.php in Gutenberg 8.3.0, at lib/template-loader.php

462 lines 16.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Block template loader functions.
4 *
5 * @package gutenberg
6 */
7
8 /**
9 * Return a list of all overrideable default template types.
10 *
11 * @see get_query_template
12 *
13 * @return string[] List of all overrideable default template types.
14 */
15 function get_template_types() {
16 return array(
17 'index',
18 '404',
19 'archive',
20 'author',
21 'category',
22 'tag',
23 'taxonomy',
24 'date',
25 'embed',
26 'home',
27 'front-page',
28 'privacy-policy',
29 'page',
30 'search',
31 'single',
32 'singular',
33 'attachment',
34 );
35 }
36
37 /**
38 * Adds necessary filters to use 'wp_template' posts instead of theme template files.
39 */
40 function gutenberg_add_template_loader_filters() {
41 if ( ! post_type_exists( 'wp_template' ) ) {
42 return;
43 }
44
45 foreach ( get_template_types() as $template_type ) {
46 if ( 'embed' === $template_type ) { // Skip 'embed' for now because it is not a regular template type.
47 continue;
48 }
49 add_filter( str_replace( '-', '', $template_type ) . '_template', 'gutenberg_override_query_template', 20, 3 );
50 }
51 }
52 add_action( 'wp_loaded', 'gutenberg_add_template_loader_filters' );
53
54 /**
55 * Get the template hierarchy for a given template type.
56 *
57 * Internally, this filters into the "{$type}_template_hierarchy" hook to record the type-specific template hierarchy.
58 *
59 * @param string $template_type A template type.
60 * @return string[] A list of template candidates, in descending order of priority.
61 */
62 function get_template_hierachy( $template_type ) {
63 if ( ! in_array( $template_type, get_template_types(), true ) ) {
64 return array();
65 }
66
67 $get_template_function = 'get_' . str_replace( '-', '_', $template_type ) . '_template'; // front-page -> get_front_page_template.
68 $template_hierarchy_filter = str_replace( '-', '', $template_type ) . '_template_hierarchy'; // front-page -> frontpage_template_hierarchy.
69
70 $result = array();
71 $template_hierarchy_filter_function = function( $templates ) use ( &$result ) {
72 $result = $templates;
73 return $templates;
74 };
75
76 add_filter( $template_hierarchy_filter, $template_hierarchy_filter_function, 20, 1 );
77 call_user_func( $get_template_function ); // This invokes template_hierarchy_filter.
78 remove_filter( $template_hierarchy_filter, $template_hierarchy_filter_function, 20 );
79
80 return $result;
81 }
82
83 /**
84 * Filters into the "{$type}_template" hooks to redirect them to the Full Site Editing template canvas.
85 *
86 * Internally, this communicates the block content that needs to be used by the template canvas through a global variable.
87 *
88 * @param string $template Path to the template. See locate_template().
89 * @param string $type Sanitized filename without extension.
90 * @param array $templates A list of template candidates, in descending order of priority.
91 * @return string The path to the Full Site Editing template canvas file.
92 */
93 function gutenberg_override_query_template( $template, $type, array $templates = array() ) {
94 global $_wp_current_template_id, $_wp_current_template_content;
95
96 $current_template = gutenberg_find_template_post_and_parts( $type, $templates );
97
98 if ( $current_template ) {
99 $_wp_current_template_id = $current_template['template_post']->ID;
100 $_wp_current_template_content = empty( $current_template['template_post']->post_content ) ? __( 'Empty template.', 'gutenberg' ) : $current_template['template_post']->post_content;
101
102 if ( isset( $_GET['_wp-find-template'] ) ) {
103 wp_send_json_success( $current_template['template_post'] );
104 }
105 } else {
106 if ( 'index' === $type ) {
107 if ( isset( $_GET['_wp-find-template'] ) ) {
108 wp_send_json_error( array( 'message' => __( 'No matching template found.', 'gutenberg' ) ) );
109 }
110 } else {
111 return false; // So that the template loader keeps looking for templates.
112 }
113 }
114
115 // Add hooks for template canvas.
116 // Add viewport meta tag.
117 add_action( 'wp_head', 'gutenberg_viewport_meta_tag', 0 );
118
119 // Render title tag with content, regardless of whether theme has title-tag support.
120 remove_action( 'wp_head', '_wp_render_title_tag', 1 ); // Remove conditional title tag rendering...
121 add_action( 'wp_head', 'gutenberg_render_title_tag', 1 ); // ...and make it unconditional.
122
123 // This file will be included instead of the theme's template file.
124 return gutenberg_dir_path() . 'lib/template-canvas.php';
125 }
126
127 /**
128 * Recursively traverses a block tree, creating auto drafts
129 * for any encountered template parts without a fixed post.
130 *
131 * @access private
132 *
133 * @param array $block The root block to start traversing from.
134 * @return int[] A list of template parts IDs for the given block.
135 */
136 function create_auto_draft_for_template_part_block( $block ) {
137 $template_part_ids = array();
138
139 if ( 'core/template-part' === $block['blockName'] ) {
140 if ( isset( $block['attrs']['postId'] ) ) {
141 // Template part is customized.
142 $template_part_id = $block['attrs']['postId'];
143 } else {
144 // A published post might already exist if this template part
145 // was customized elsewhere or if it's part of a customized
146 // template. We also check if an auto-draft was already created
147 // because preloading can make this run twice, so, different code
148 // paths can end up with different posts for the same template part.
149 // E.g. The server could send back post ID 1 to the client, preload,
150 // and create another auto-draft. So, if the client tries to resolve the
151 // post ID from the slug and theme, it won't match with what the server sent.
152 $template_part_query = new WP_Query(
153 array(
154 'post_type' => 'wp_template_part',
155 'post_status' => array( 'publish', 'auto-draft' ),
156 'name' => $block['attrs']['slug'],
157 'meta_key' => 'theme',
158 'meta_value' => $block['attrs']['theme'],
159 'posts_per_page' => 1,
160 'no_found_rows' => true,
161 )
162 );
163 $template_part_post = $template_part_query->have_posts() ? $template_part_query->next_post() : null;
164 if ( $template_part_post ) {
165 $template_part_id = $template_part_post->ID;
166 } else {
167 // Template part is not customized, get it from a file and make an auto-draft for it.
168 $template_part_file_path =
169 get_stylesheet_directory() . '/block-template-parts/' . $block['attrs']['slug'] . '.html';
170 if ( ! file_exists( $template_part_file_path ) ) {
171 if ( gutenberg_is_experiment_enabled( 'gutenberg-full-site-editing-demo' ) ) {
172 $template_part_file_path =
173 dirname( __FILE__ ) . '/demo-block-template-parts/' . $block['attrs']['slug'] . '.html';
174 if ( ! file_exists( $template_part_file_path ) ) {
175 return;
176 }
177 } else {
178 return;
179 }
180 }
181 $template_part_id = wp_insert_post(
182 array(
183 'post_content' => file_get_contents( $template_part_file_path ),
184 'post_title' => $block['attrs']['slug'],
185 'post_status' => 'auto-draft',
186 'post_type' => 'wp_template_part',
187 'post_name' => $block['attrs']['slug'],
188 'meta_input' => array(
189 'theme' => $block['attrs']['theme'],
190 ),
191 )
192 );
193 }
194 }
195 $template_part_ids[ $block['attrs']['slug'] ] = $template_part_id;
196 }
197
198 foreach ( $block['innerBlocks'] as $inner_block ) {
199 $template_part_ids = array_merge( $template_part_ids, create_auto_draft_for_template_part_block( $inner_block ) );
200 }
201 return $template_part_ids;
202 }
203
204 /**
205 * Return the correct 'wp_template' post and template part IDs for the current template.
206 *
207 * Accepts an optional $template_hierarchy argument as a hint.
208 *
209 * @param string $template_type The current template type.
210 * @param string[] $template_hierarchy (optional) The current template hierarchy, ordered by priority.
211 * @return null|array {
212 * @type WP_Post|null template_post A template post object, or null if none could be found.
213 * @type int[] A list of template parts IDs for the template.
214 * }
215 */
216 function gutenberg_find_template_post_and_parts( $template_type, $template_hierarchy = array() ) {
217 if ( ! $template_type ) {
218 return null;
219 }
220
221 if ( empty( $template_hierarchy ) ) {
222 if ( 'index' === $template_type ) {
223 $template_hierarchy = get_template_hierachy( 'index' );
224 } else {
225 $template_hierarchy = array_merge( get_template_hierachy( $template_type ), get_template_hierachy( 'index' ) );
226 }
227 }
228
229 $slugs = array_map(
230 'gutenberg_strip_php_suffix',
231 $template_hierarchy
232 );
233
234 // Find most specific 'wp_template' post matching the hierarchy.
235 $template_query = new WP_Query(
236 array(
237 'post_type' => 'wp_template',
238 'post_status' => 'publish',
239 'post_name__in' => $slugs,
240 'orderby' => 'post_name__in',
241 'posts_per_page' => 1,
242 'no_found_rows' => true,
243 )
244 );
245
246 $current_template_post = $template_query->have_posts() ? $template_query->next_post() : null;
247
248 // Build map of template slugs to their priority in the current hierarchy.
249 $slug_priorities = array_flip( $slugs );
250
251 // See if there is a theme block template with higher priority than the resolved template post.
252 $higher_priority_block_template_path = null;
253 $higher_priority_block_template_priority = PHP_INT_MAX;
254 $block_template_files = glob( get_stylesheet_directory() . '/block-templates/*.html' );
255 $block_template_files = is_array( $block_template_files ) ? $block_template_files : array();
256 if ( is_child_theme() ) {
257 $child_block_template_files = glob( get_template_directory() . '/block-templates/*.html' );
258 $child_block_template_files = is_array( $child_block_template_files ) ? $child_block_template_files : array();
259 $block_template_files = array_merge( $block_template_files, $child_block_template_files );
260 }
261 if ( gutenberg_is_experiment_enabled( 'gutenberg-full-site-editing-demo' ) ) {
262 $demo_block_template_files = glob( dirname( __FILE__ ) . '/demo-block-templates/*.html' );
263 $demo_block_template_files = is_array( $demo_block_template_files ) ? $demo_block_template_files : array();
264 $block_template_files = array_merge( $block_template_files, $demo_block_template_files );
265 }
266 foreach ( $block_template_files as $path ) {
267 if ( ! isset( $slug_priorities[ basename( $path, '.html' ) ] ) ) {
268 continue;
269 }
270 $theme_block_template_priority = $slug_priorities[ basename( $path, '.html' ) ];
271 if (
272 $theme_block_template_priority < $higher_priority_block_template_priority &&
273 ( empty( $current_template_post ) || $theme_block_template_priority < $slug_priorities[ $current_template_post->post_name ] )
274 ) {
275 $higher_priority_block_template_path = $path;
276 $higher_priority_block_template_priority = $theme_block_template_priority;
277 }
278 }
279
280 // If there is, use it instead.
281 if ( isset( $higher_priority_block_template_path ) ) {
282 $post_name = basename( $higher_priority_block_template_path, '.html' );
283 $file_contents = file_get_contents( $higher_priority_block_template_path );
284 $current_template_post = array(
285 'post_content' => $file_contents,
286 'post_title' => $post_name,
287 'post_status' => 'auto-draft',
288 'post_type' => 'wp_template',
289 'post_name' => $post_name,
290 );
291 if ( is_admin() || defined( 'REST_REQUEST' ) ) {
292 $template_query = new WP_Query(
293 array(
294 'post_type' => 'wp_template',
295 'post_status' => 'auto-draft',
296 'name' => $post_name,
297 'posts_per_page' => 1,
298 'no_found_rows' => true,
299 )
300 );
301 $current_template_post = $template_query->have_posts() ? $template_query->next_post() : $current_template_post;
302
303 // Only create auto-draft of block template for editing
304 // in admin screens, when necessary, because the underlying
305 // file has changed.
306 if ( is_array( $current_template_post ) || $current_template_post->post_content !== $file_contents ) {
307 if ( ! is_array( $current_template_post ) ) {
308 $current_template_post->post_content = $file_contents;
309 }
310 $current_template_post = get_post(
311 wp_insert_post( $current_template_post )
312 );
313 }
314 } else {
315 $current_template_post = new WP_Post(
316 (object) $current_template_post
317 );
318 }
319 }
320
321 // If we haven't found any template post by here, it means that this theme doesn't even come with a fallback
322 // `index.html` block template. We create one so that people that are trying to access the editor are greeted
323 // with a blank page rather than an error.
324 if ( ! $current_template_post && ( is_admin() || defined( 'REST_REQUEST' ) ) ) {
325 $current_template_post = array(
326 'post_title' => 'index',
327 'post_status' => 'auto-draft',
328 'post_type' => 'wp_template',
329 'post_name' => 'index',
330 );
331 $current_template_post = get_post(
332 wp_insert_post( $current_template_post )
333 );
334 }
335
336 if ( $current_template_post ) {
337 $template_part_ids = array();
338 if ( is_admin() ) {
339 foreach ( parse_blocks( $current_template_post->post_content ) as $block ) {
340 $template_part_ids = array_merge( $template_part_ids, create_auto_draft_for_template_part_block( $block ) );
341 }
342 }
343 return array(
344 'template_post' => $current_template_post,
345 'template_part_ids' => $template_part_ids,
346 );
347 }
348 return null;
349 }
350
351 /**
352 * Displays title tag with content, regardless of whether theme has title-tag support.
353 *
354 * @see _wp_render_title_tag()
355 */
356 function gutenberg_render_title_tag() {
357 echo '<title>' . wp_get_document_title() . '</title>' . "\n";
358 }
359
360 /**
361 * Renders the markup for the current template.
362 */
363 function gutenberg_render_the_template() {
364 global $_wp_current_template_content;
365 global $wp_embed;
366
367 if ( ! $_wp_current_template_content ) {
368 echo '<h1>' . esc_html__( 'No matching template found', 'gutenberg' ) . '</h1>';
369 return;
370 }
371
372 $content = $wp_embed->run_shortcode( $_wp_current_template_content );
373 $content = $wp_embed->autoembed( $content );
374 $content = do_blocks( $content );
375 $content = wptexturize( $content );
376 if ( function_exists( 'wp_filter_content_tags' ) ) {
377 $content = wp_filter_content_tags( $content );
378 } else {
379 $content = wp_make_content_images_responsive( $content );
380 }
381 $content = str_replace( ']]>', ']]&gt;', $content );
382
383 // Wrap block template in .wp-site-blocks to allow for specific descendant styles
384 // (e.g. `.wp-site-blocks > *`).
385 echo '<div class="wp-site-blocks">';
386 echo $content; // phpcs:ignore WordPress.Security.EscapeOutput
387 echo '</div>';
388 }
389
390 /**
391 * Renders a 'viewport' meta tag.
392 *
393 * This is hooked into {@see 'wp_head'} to decouple its output from the default template canvas.
394 */
395 function gutenberg_viewport_meta_tag() {
396 echo '<meta name="viewport" content="width=device-width, initial-scale=1" />' . "\n";
397 }
398
399 /**
400 * Strips .php suffix from template file names.
401 *
402 * @access private
403 *
404 * @param string $template_file Template file name.
405 * @return string Template file name without extension.
406 */
407 function gutenberg_strip_php_suffix( $template_file ) {
408 return preg_replace( '/\.php$/', '', $template_file );
409 }
410
411 /**
412 * Extends default editor settings to enable template and template part editing.
413 *
414 * @param array $settings Default editor settings.
415 *
416 * @return array Filtered editor settings.
417 */
418 function gutenberg_template_loader_filter_block_editor_settings( $settings ) {
419 global $post, $_wp_current_template_id;
420
421 if ( ! $post || ! post_type_exists( 'wp_template' ) || ! post_type_exists( 'wp_template_part' ) ) {
422 return $settings;
423 }
424
425 // Create template part auto-drafts for the edited post.
426 $post = isset( $_wp_current_template_id )
427 ? get_post( $_wp_current_template_id ) // It's a template.
428 : get_post(); // It's a post.
429 foreach ( parse_blocks( $post->post_content ) as $block ) {
430 create_auto_draft_for_template_part_block( $block );
431 }
432
433 // TODO: Set editing mode and current template ID for editing modes support.
434 return $settings;
435 }
436 add_filter( 'block_editor_settings', 'gutenberg_template_loader_filter_block_editor_settings' );
437
438 /**
439 * Removes post details from block context when rendering a block template.
440 *
441 * @param array $context Default context.
442 *
443 * @return array Filtered context.
444 */
445 function gutenberg_template_render_without_post_block_context( $context ) {
446 /*
447 * When loading a template or template part directly and not through a page
448 * that resolves it, the top-level post ID and type context get set to that
449 * of the template part. Templates are just the structure of a site, and
450 * they should not be available as post context because blocks like Post
451 * Content would recurse infinitely.
452 */
453 if ( isset( $context['postType'] ) &&
454 ( 'wp_template' === $context['postType'] || 'wp_template_part' === $context['postType'] ) ) {
455 unset( $context['postId'] );
456 unset( $context['postType'] );
457 }
458
459 return $context;
460 }
461 add_filter( 'render_block_context', 'gutenberg_template_render_without_post_block_context' );
462