Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FSE: Pre-populate template with fallback upon creation #42007

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/compat/wordpress-6.1/block-template-utils.php
Expand Up @@ -165,6 +165,22 @@ function gutenberg_get_block_templates( $query = array(), $template_type = 'wp_t
return apply_filters( 'get_block_templates', $query_result, $query, $template_type );
}

function gutenberg_get_template_slugs( $template ) {
$limit = 2;
if ( strpos( $template, 'single-' ) === 0 || strpos( $template, 'taxonomy-' ) === 0 ) {
// E.g. single-post-mypost or taxonomy-recipes-vegetarian.
$limit = 3;
}
$parts = explode( '-', $template, $limit );
$type = array_shift( $parts );
$slugs = array( $type );

foreach ( $parts as $part ) {
array_unshift( $slugs, $slugs[0] . '-' . $part );
}
return $slugs;
}

/**
* Retrieves a single unified template object using its id.
*
Expand Down
Expand Up @@ -194,10 +194,17 @@ protected function prepare_item_for_database( $request ) {
$changes->ID = $template->wp_id;
$changes->post_status = 'publish';
}
if ( isset( $request['content'] ) ) {
if ( isset( $request['content'] ) && ! empty( $request['content'] ) ) {
$changes->post_content = $request['content'];
} elseif ( null !== $template && 'custom' !== $template->source ) {
$changes->post_content = $template->content;
} elseif ( null === $template && empty( $request['content'] ) ) {
$fallback_templates = gutenberg_get_template_slugs( $request['slug'] );
$fallback_template = resolve_block_template( $request['slug'], $fallback_templates, '' );
if ( ! $fallback_template ) {
$fallback_template = resolve_block_template( 'index', array(), '' );
}
$changes->post_content = $fallback_template->content;
}
if ( isset( $request['title'] ) ) {
$changes->post_title = $request['title'];
Expand Down
26 changes: 26 additions & 0 deletions phpunit/compat/wordpress-6.1/block-template-utils-test.php
@@ -0,0 +1,26 @@
<?php
/**
* Tests_Block_Template_Utils class
*
* @package gutenberg
*/

/**
* Tests for the Block Templates abstraction layer.
*
* @group block-templates
*/
class Tests_Block_Template_Utils_6_1 extends WP_UnitTestCase {
public function test_get_template_slugs() {
$templates = gutenberg_get_template_slugs( 'single-post-hello-world' );
$this->assertSame(
array(
'single-post-hello-world',
// Should *not* fall back to `single-post-hello`!
'single-post',
'single',
),
$templates
);
}
}