From 886600a086c0664a23c15d8a995d34f60c5cb6f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A4nk=20Klein?= Date: Mon, 19 Oct 2020 15:02:19 +0200 Subject: [PATCH] Strip post ids from template part blocks on export. This ensures that exported FSE themes work on other sites. --- lib/edit-site-export.php | 31 ++++++++++++++++++++++++- phpunit/bootstrap.php | 1 + phpunit/class-edit-site-export-test.php | 29 +++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 phpunit/class-edit-site-export-test.php diff --git a/lib/edit-site-export.php b/lib/edit-site-export.php index c62fb42c2c930..8967788bdf8a1 100644 --- a/lib/edit-site-export.php +++ b/lib/edit-site-export.php @@ -28,7 +28,10 @@ function gutenberg_edit_site_export() { $current_template = gutenberg_find_template_post_and_parts( $template_type ); if ( isset( $current_template ) ) { - $zip->addFromString( 'theme/block-templates/' . $current_template['template_post']->post_name . '.html', $current_template['template_post']->post_content ); + $zip->addFromString( + 'theme/block-templates/' . $current_template['template_post']->post_name . '.html', + gutenberg_strip_post_ids_from_template_part_blocks( $current_template['template_post']->post_content ) + ); foreach ( $current_template['template_part_ids'] as $template_part_id ) { $template_part = get_post( $template_part_id ); @@ -62,3 +65,29 @@ function () { ); } ); + +/** + * Remove post id attributes from template part blocks. + * + * This is needed so that Gutenberg loads the HTML file of the template, instead of looking for a template part post. + * + * @param string $template_content Template content to modify. + * + * @return string Potentially modified template content. + */ +function gutenberg_strip_post_ids_from_template_part_blocks( $template_content ) { + $blocks = parse_blocks( $template_content ); + + array_walk( + $blocks, + function( &$block ) { + if ( 'core/template-part' !== $block['blockName'] ) { + return; + } + + unset( $block['attrs']['postId'] ); + } + ); + + return serialize_blocks( $blocks ); +} diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php index ca8ab6fa0d66e..0b1653cc3c9fd 100644 --- a/phpunit/bootstrap.php +++ b/phpunit/bootstrap.php @@ -73,6 +73,7 @@ function fail_if_died( $message ) { $GLOBALS['wp_tests_options'] = array( 'gutenberg-experiments' => array( 'gutenberg-widget-experiments' => '1', + 'gutenberg-full-site-editing' => 1, ), ); diff --git a/phpunit/class-edit-site-export-test.php b/phpunit/class-edit-site-export-test.php new file mode 100644 index 0000000000000..5b7ddbe7f7785 --- /dev/null +++ b/phpunit/class-edit-site-export-test.php @@ -0,0 +1,29 @@ +post->create_and_get( + array( + 'post_content' => '', + 'post_title' => 'Archive', + 'post_type' => 'wp_template', + ) + ); + + $this->assertSame( + '', + gutenberg_strip_post_ids_from_template_part_blocks( $post->post_content ) + ); + } +}