diff --git a/src/wp-includes/block-template.php b/src/wp-includes/block-template.php index 945b96b027422..e96200b18d75e 100644 --- a/src/wp-includes/block-template.php +++ b/src/wp-includes/block-template.php @@ -5,6 +5,31 @@ * @package WordPress */ +/** + * Adds necessary filters to use 'wp_template' posts instead of theme template files. + * + * @access private + * @since 5.9.0 + */ +function _add_template_loader_filters() { + if ( ! current_theme_supports( 'block-templates' ) ) { + return; + } + + $template_types = array_keys( get_default_block_template_types() ); + foreach ( $template_types as $template_type ) { + if ( 'embed' === $template_type ) { // Skip 'embed' for now because it is not a regular template type. + continue; + } + add_filter( str_replace( '-', '', $template_type ) . '_template', 'locate_block_template', 20, 3 ); + } + + // Request to resolve a template. + if ( isset( $_GET['_wp-find-template'] ) ) { + add_filter( 'pre_get_posts', '_resolve_template_for_new_post' ); + } +} + /** * Find a block template with equal or higher specificity than a given PHP template file. * @@ -227,3 +252,35 @@ function _block_template_render_without_post_block_context( $context ) { return $context; } + +/** + * Sets the current WP_Query to return auto-draft posts. + * + * The auto-draft status indicates a new post, so allow the the WP_Query instance to + * return an auto-draft post for template resolution when editing a new post. + * + * @access private + * @since 5.9.0 + * + * @param WP_Query $wp_query Current WP_Query instance, passed by reference. + */ +function _resolve_template_for_new_post( $wp_query ) { + remove_filter( 'pre_get_posts', '_resolve_template_for_new_post' ); + + // Pages. + $page_id = isset( $wp_query->query['page_id'] ) ? $wp_query->query['page_id'] : null; + + // Posts, including custom post types. + $p = isset( $wp_query->query['p'] ) ? $wp_query->query['p'] : null; + + $post_id = $page_id ? $page_id : $p; + $post = get_post( $post_id ); + + if ( + $post && + 'auto-draft' === $post->post_status && + current_user_can( 'edit_post', $post->ID ) + ) { + $wp_query->set( 'post_status', 'auto-draft' ); + } +} diff --git a/src/wp-includes/default-filters.php b/src/wp-includes/default-filters.php index 24396236484ff..23b0035d8fb3e 100644 --- a/src/wp-includes/default-filters.php +++ b/src/wp-includes/default-filters.php @@ -680,5 +680,6 @@ add_action( 'save_post_wp_template_part', 'wp_set_unique_slug_on_create_template_part' ); add_action( 'wp_footer', 'the_block_template_skip_link' ); add_action( 'setup_theme', 'wp_enable_block_templates' ); +add_action( 'wp_loaded', '_add_template_loader_filters' ); unset( $filter, $action );