我创建了一个块模板,以便每个新帖子都从特定的块集合开始。
在下面的简化示例中,假设块模板只包含标题块和段落块(实际上,块模板要复杂得多):
function register_custom_block_template() {
$post_type_object = get_post_type_object( \'post\' );
$post_type_object->template = array(
array( \'core/heading\', array(
\'placeholder\' => \'Post Heading\',
) ),
array( \'core/paragraph\', array(
\'placeholder\' => \'Post Paragraph\',
) ),
);
}
add_action( \'init\', \'register_custom_block_template\' );
有时,基于某个动作,我想通过编程添加一篇帖子,使用
wp_insert_post()
将使用相同或类似的块样板。但是,为了在wp\\u insert\\u post数组的“post\\u content”键中添加相同的块,我必须手动将块模板的所有PHP数组重写为块编辑器使用的HTML/注释格式:
// Programatically insert new post
wp_insert_post(
array(
\'post_title\' => \'Test Post\',
\'post_content\' => \'
<!-- wp:heading {"placeholder":"Post Heading"} -->
<h2></h2>
<!-- /wp:heading -->
<!-- wp:paragraph {"placeholder":"Post Paragraph"} -->
<p></p>
<!-- /wp:paragraph -->\',
\'post_status\' => \'publish\',
\'post_author\' => 1,
)
);
如何在内部重用块模板的PHP数组
wp_insert_post()
i、 通过将数组添加到公共变量。WordPress应该是这样做的,因为当创建一篇新文章时,块模板将从PHP/数组转换为新文章中的HTML/注释,所以核心中一定有某种函数?
我最需要的是这样的东西:
// Block Template
$block_template = array(
array( \'core/heading\', array(
\'placeholder\' => \'Post Heading\',
) ),
array( \'core/paragraph\', array(
\'placeholder\' => \'Post Paragraph\',
) ),
);
// Post Template (for newly created posts)
function register_custom_block_template() {
$post_type_object = get_post_type_object( \'post\' );
$post_type_object->template = $block_template;
}
add_action( \'init\', \'register_custom_block_template\' );
// Programatically insert new post
wp_insert_post(
array(
\'post_title\' => \'Test Post\',
\'post_content\' => $block_template,
\'post_status\' => \'publish\',
\'post_author\' => 1,
)
);