我希望能够采用在古腾堡编辑器中设计的块或另存为 .html 模板文件,并将它们转换为我可以在注册自定义 block.json 或帖子类型时使用的模板。
例如,这就是我在编辑器中的内容:
<!-- wp:heading {"level":1,"className":"display-4"} -->
<h1 class="wp-block-heading display-4">Hello World</h1>
<!-- /wp:heading -->
接下来我必须输入所有带有支撑和属性的块,如果有很多嵌套块,那就非常粗糙了:
function myplugin_register_book_post_type() {
$args = array(
...
'template' => array(
array( 'core/heading', array(
'placeholder' => 'Add Author...',
) )
),
template_lock => 'insert';
);
register_post_type( 'book', $args );
}
add_action( 'init', 'myplugin_register_book_post_type' );
我正在寻找 PHP 或 JS 中的一个函数,可以将块 HTML 转换为模板数组。
由于您可以使用 FSE 主题编辑器为特定帖子创建模板,因此我假设有一个函数可以完成我在某处寻找的功能。
我尝试使用parse_blocks:
function myplugin_register_book_post_type() {
$args = array(
'template' => parse_blocks('<!-- wp:heading {"level":1,"className":"display-4"} -->
<h1 class="wp-block-heading display-4">Hello World</h1>
<!-- /wp:heading -->'),
template_lock => 'insert';
);
register_post_type( 'book', $args );
}
add_action( 'init', 'myplugin_register_book_post_type' );
但这并没有产生相同的格式。
我研究了 WordPress 核心代码,但似乎找不到可以进行此类转换的东西。
我检查了 Codex 中的文档,搜索了 Github 和 Google。但很难得到有意义的结果,因为 WordPress 上下文中的“模板”通常指的是主题模板文件,而不是块注册。到目前为止,在所有不断变化的文档中最有用的资源是这个很棒的网站:https://fullsiteediting.com/lessons/creating-block-templates-for-custom-post-types/
感谢您的帮助!这是我在这里发表的第一篇文章,我确信我遗漏了一些明显的东西。让 Google 返回我这些天实际寻找的结果似乎更困难。
我仍然不知道如何将块从 HTML 转换为 PHP,但我找到了两种解决方法来避免这样做。还不确定我更喜欢哪种方法。
core/pattern
块如此处所述,您可以将 HTML 保存为模式并将其用作模板。按照您喜欢的方式注册模式,或者完全使用 PHP:
register_block_pattern( 'my_theme/my_pattern_slug', array(
'title' => 'Custom Post Type Template',
'content' => '{HTML FROM EDITOR}'
) );
/patterns
目录中,并为模式文件头添加 PHP 注释:
<?php
/**
* Title: Custom Post Type Template
* Slug: my_theme/my_pattern_slug
*/
?>
{HTML FROM EDITOR}
然后您可以将自定义帖子类型模板设置为加载新模式的
core/pattern
块。
$args = array(
...
'template' => array(
array(
'core/pattern',
array(
'slug' => 'my_theme/my_pattern_slug' )
),
)
)
}
default_content
过滤器如here所述,您可以使用
default_content
过滤器而不用设置模板:
function my_custom_post_type_template( $content, $post ) {
if ( $post->post_type === 'my_custom_post_type' ) {
$content = '{HTML FROM EDITOR}';
}
return $content;
}
add_filter('default_content', 'my_custom_post_type_template', 10, 2);