PluginProbe
Gutenberg / 8.2.0
Gutenberg v8.2.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.2.0, at lib/template-loader.php

448 lines 15.6 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 if ( 'core/template-part' !== $block['blockName'] ) {
138 return array();
139 }
140
141 if ( isset( $block['attrs']['postId'] ) ) {
142 // Template part is customized.
143 $template_part_id = $block['attrs']['postId'];
144 } else {
145 // A published post might already exist if this template part
146 // was customized elsewhere or if it's part of a customized
147 // template. We also check if an auto-draft was already created
148 // because preloading can make this run twice, so, different code
149 // paths can end up with different posts for the same template part.
150 // E.g. The server could send back post ID 1 to the client, preload,
151 // and create another auto-draft. So, if the client tries to resolve the
152 // post ID from the slug and theme, it won't match with what the server sent.
153 $template_part_query = new WP_Query(
154 array(
155 'post_type' => 'wp_template_part',
156 'post_status' => array( 'publish', 'auto-draft' ),
157 'name' => $block['attrs']['slug'],
158 'meta_key' => 'theme',
159 'meta_value' => $block['attrs']['theme'],
160 'posts_per_page' => 1,
161 'no_found_rows' => true,
162 )
163 );
164 $template_part_post = $template_part_query->have_posts() ? $template_part_query->next_post() : null;
165 if ( $template_part_post ) {
166 $template_part_id = $template_part_post->ID;
167 } else {
168 // Template part is not customized, get it from a file and make an auto-draft for it.
169 $template_part_file_path =
170 get_stylesheet_directory() . '/block-template-parts/' . $block['attrs']['slug'] . '.html';
171 if ( ! file_exists( $template_part_file_path ) ) {
172 if ( gutenberg_is_experiment_enabled( 'gutenberg-full-site-editing-demo' ) ) {
173 $template_part_file_path =
174 dirname( __FILE__ ) . '/demo-block-template-parts/' . $block['attrs']['slug'] . '.html';
175 if ( ! file_exists( $template_part_file_path ) ) {
176 return;
177 }
178 } else {
179 return;
180 }
181 }
182 $template_part_id = wp_insert_post(
183 array(
184 'post_content' => file_get_contents( $template_part_file_path ),
185 'post_title' => $block['attrs']['slug'],
186 'post_status' => 'auto-draft',
187 'post_type' => 'wp_template_part',
188 'post_name' => $block['attrs']['slug'],
189 'meta_input' => array(
190 'theme' => $block['attrs']['theme'],
191 ),
192 )
193 );
194 }
195 }
196
197 $template_part_ids = array( $block['attrs']['slug'] => $template_part_id );
198
199 foreach ( $block['innerBlocks'] as $inner_block ) {
200 $template_part_ids = array_merge( $template_part_ids, create_auto_draft_for_template_part_block( $inner_block ) );
201 }
202 return $template_part_ids;
203 }
204
205 /**
206 * Return the correct 'wp_template' post and template part IDs for the current template.
207 *
208 * Accepts an optional $template_hierarchy argument as a hint.
209 *
210 * @param string $template_type The current template type.
211 * @param string[] $template_hierarchy (optional) The current template hierarchy, ordered by priority.
212 * @return null|array {
213 * @type WP_Post|null template_post A template post object, or null if none could be found.
214 * @type int[] A list of template parts IDs for the template.
215 * }
216 */
217 function gutenberg_find_template_post_and_parts( $template_type, $template_hierarchy = array() ) {
218 if ( ! $template_type ) {
219 return null;
220 }
221
222 if ( empty( $template_hierarchy ) ) {
223 if ( 'index' === $template_type ) {
224 $template_hierarchy = get_template_hierachy( 'index' );
225 } else {
226 $template_hierarchy = array_merge( get_template_hierachy( $template_type ), get_template_hierachy( 'index' ) );
227 }
228 }
229
230 $slugs = array_map(
231 'gutenberg_strip_php_suffix',
232 $template_hierarchy
233 );
234
235 // Find most specific 'wp_template' post matching the hierarchy.
236 $template_query = new WP_Query(
237 array(
238 'post_type' => 'wp_template',
239 'post_status' => 'publish',
240 'post_name__in' => $slugs,
241 'orderby' => 'post_name__in',
242 'posts_per_page' => 1,
243 'no_found_rows' => true,
244 )
245 );
246
247 $current_template_post = $template_query->have_posts() ? $template_query->next_post() : null;
248
249 // Build map of template slugs to their priority in the current hierarchy.
250 $slug_priorities = array_flip( $slugs );
251
252 // See if there is a theme block template with higher priority than the resolved template post.
253 $higher_priority_block_template_path = null;
254 $higher_priority_block_template_priority = PHP_INT_MAX;
255 $block_template_files = glob( get_stylesheet_directory() . '/block-templates/*.html' );
256 $block_template_files = is_array( $block_template_files ) ? $block_template_files : array();
257 if ( is_child_theme() ) {
258 $child_block_template_files = glob( get_template_directory() . '/block-templates/*.html' );
259 $child_block_template_files = is_array( $child_block_template_files ) ? $child_block_template_files : array();
260 $block_template_files = array_merge( $block_template_files, $child_block_template_files );
261 }
262 if ( gutenberg_is_experiment_enabled( 'gutenberg-full-site-editing-demo' ) ) {
263 $demo_block_template_files = glob( dirname( __FILE__ ) . '/demo-block-templates/*.html' );
264 $demo_block_template_files = is_array( $demo_block_template_files ) ? $demo_block_template_files : array();
265 $block_template_files = array_merge( $block_template_files, $demo_block_template_files );
266 }
267 foreach ( $block_template_files as $path ) {
268 if ( ! isset( $slug_priorities[ basename( $path, '.html' ) ] ) ) {
269 continue;
270 }
271 $theme_block_template_priority = $slug_priorities[ basename( $path, '.html' ) ];
272 if (
273 $theme_block_template_priority < $higher_priority_block_template_priority &&
274 ( empty( $current_template_post ) || $theme_block_template_priority < $slug_priorities[ $current_template_post->post_name ] )
275 ) {
276 $higher_priority_block_template_path = $path;
277 $higher_priority_block_template_priority = $theme_block_template_priority;
278 }
279 }
280
281 // If there is, use it instead.
282 if ( isset( $higher_priority_block_template_path ) ) {
283 $post_name = basename( $higher_priority_block_template_path, '.html' );
284 $file_contents = file_get_contents( $higher_priority_block_template_path );
285 $current_template_post = array(
286 'post_content' => $file_contents,
287 'post_title' => $post_name,
288 'post_status' => 'auto-draft',
289 'post_type' => 'wp_template',
290 'post_name' => $post_name,
291 );
292 if ( is_admin() || defined( 'REST_REQUEST' ) ) {
293 $template_query = new WP_Query(
294 array(
295 'post_type' => 'wp_template',
296 'post_status' => 'auto-draft',
297 'name' => $post_name,
298 'posts_per_page' => 1,
299 'no_found_rows' => true,
300 )
301 );
302 $current_template_post = $template_query->have_posts() ? $template_query->next_post() : $current_template_post;
303
304 // Only create auto-draft of block template for editing
305 // in admin screens, when necessary, because the underlying
306 // file has changed.
307 if ( is_array( $current_template_post ) || $current_template_post->post_content !== $file_contents ) {
308 if ( ! is_array( $current_template_post ) ) {
309 $current_template_post->post_content = $file_contents;
310 }
311 $current_template_post = get_post(
312 wp_insert_post( $current_template_post )
313 );
314 }
315 } else {
316 $current_template_post = new WP_Post(
317 (object) $current_template_post
318 );
319 }
320 }
321
322 if ( $current_template_post ) {
323 $template_part_ids = array();
324 if ( is_admin() ) {
325 foreach ( parse_blocks( $current_template_post->post_content ) as $block ) {
326 $template_part_ids = array_merge( $template_part_ids, create_auto_draft_for_template_part_block( $block ) );
327 }
328 }
329 return array(
330 'template_post' => $current_template_post,
331 'template_part_ids' => $template_part_ids,
332 );
333 }
334 return null;
335 }
336
337 /**
338 * Displays title tag with content, regardless of whether theme has title-tag support.
339 *
340 * @see _wp_render_title_tag()
341 */
342 function gutenberg_render_title_tag() {
343 echo '<title>' . wp_get_document_title() . '</title>' . "\n";
344 }
345
346 /**
347 * Renders the markup for the current template.
348 */
349 function gutenberg_render_the_template() {
350 global $_wp_current_template_content;
351 global $wp_embed;
352
353 if ( ! $_wp_current_template_content ) {
354 echo '<h1>' . esc_html__( 'No matching template found', 'gutenberg' ) . '</h1>';
355 return;
356 }
357
358 $content = $wp_embed->run_shortcode( $_wp_current_template_content );
359 $content = $wp_embed->autoembed( $content );
360 $content = do_blocks( $content );
361 $content = wptexturize( $content );
362 if ( function_exists( 'wp_filter_content_tags' ) ) {
363 $content = wp_filter_content_tags( $content );
364 } else {
365 $content = wp_make_content_images_responsive( $content );
366 }
367 $content = str_replace( ']]>', ']]&gt;', $content );
368
369 // Wrap block template in .wp-site-blocks to allow for specific descendant styles
370 // (e.g. `.wp-site-blocks > *`).
371 echo '<div class="wp-site-blocks">';
372 echo $content; // phpcs:ignore WordPress.Security.EscapeOutput
373 echo '</div>';
374 }
375
376 /**
377 * Renders a 'viewport' meta tag.
378 *
379 * This is hooked into {@see 'wp_head'} to decouple its output from the default template canvas.
380 */
381 function gutenberg_viewport_meta_tag() {
382 echo '<meta name="viewport" content="width=device-width, initial-scale=1" />' . "\n";
383 }
384
385 /**
386 * Strips .php suffix from template file names.
387 *
388 * @access private
389 *
390 * @param string $template_file Template file name.
391 * @return string Template file name without extension.
392 */
393 function gutenberg_strip_php_suffix( $template_file ) {
394 return preg_replace( '/\.php$/', '', $template_file );
395 }
396
397 /**
398 * Extends default editor settings to enable template and template part editing.
399 *
400 * @param array $settings Default editor settings.
401 *
402 * @return array Filtered editor settings.
403 */
404 function gutenberg_template_loader_filter_block_editor_settings( $settings ) {
405 global $post, $_wp_current_template_id;
406
407 if ( ! $post || ! post_type_exists( 'wp_template' ) || ! post_type_exists( 'wp_template_part' ) ) {
408 return $settings;
409 }
410
411 // Create template part auto-drafts for the edited post.
412 $post = isset( $_wp_current_template_id )
413 ? get_post( $_wp_current_template_id ) // It's a template.
414 : get_post(); // It's a post.
415 foreach ( parse_blocks( $post->post_content ) as $block ) {
416 create_auto_draft_for_template_part_block( $block );
417 }
418
419 // TODO: Set editing mode and current template ID for editing modes support.
420 return $settings;
421 }
422 add_filter( 'block_editor_settings', 'gutenberg_template_loader_filter_block_editor_settings' );
423
424 /**
425 * Removes post details from block context when rendering a block template.
426 *
427 * @param array $context Default context.
428 *
429 * @return array Filtered context.
430 */
431 function gutenberg_template_render_without_post_block_context( $context ) {
432 /*
433 * When loading a template or template part directly and not through a page
434 * that resolves it, the top-level post ID and type context get set to that
435 * of the template part. Templates are just the structure of a site, and
436 * they should not be available as post context because blocks like Post
437 * Content would recurse infinitely.
438 */
439 if ( isset( $context['postType'] ) &&
440 ( 'wp_template' === $context['postType'] || 'wp_template_part' === $context['postType'] ) ) {
441 unset( $context['postId'] );
442 unset( $context['postType'] );
443 }
444
445 return $context;
446 }
447 add_filter( 'render_block_context', 'gutenberg_template_render_without_post_block_context' );
448