admin管理员组文章数量:1122832
forgive me a question that may seem stupid, but has been keeping me busy for hours: I'm trying to insert a gutenberg block into a category php template, but neither the render_block () function nor the do_blocks () function seem to give results. Can anyone help me?
forgive me a question that may seem stupid, but has been keeping me busy for hours: I'm trying to insert a gutenberg block into a category php template, but neither the render_block () function nor the do_blocks () function seem to give results. Can anyone help me?
Share Improve this question asked Jul 21, 2022 at 9:40 Luca PisoniLuca Pisoni 1317 bronze badges 2- 2 There isn't really an API for rendering a block directly into a PHP template. You would need to add one to a post, copy the HTML, and use that in the template. – Jacob Peattie Commented Jul 21, 2022 at 10:38
- Please provide more specific details on what you're trying to do. – djanym Commented Jul 22, 2022 at 15:07
2 Answers
Reset to default 2Unfortunately, most blocks in Gutenberg use JavaScript to convert their settings/content into HTML code (via the React component's save()
function).
So when you click "Update Post", each block on the page reports its HTML output via JavaScript/React and that combined output is sent to the backend to save to the post_content.
So there's no equivalent way to get the rendered HTML via PHP.
What you can do is pass the markup that's saved in post_content to a few Wordpress functions and it will handle the rest (rendering child blocks, queueing scripts and stylesheets, finishing some HTML markup etc).
For example:
$serialisedAttributes = serialize_block_attributes([
'url' => 'https://www.youtube.com/watch?v=h7wcvHoxxo0',
'providerNameSlug' => 'youtube',
'type' => 'video',
'className' => 'wp-embed-aspect-16-9 wp-has-aspect-ratio'
]);
$code = "<!-- wp:embed $serialisedAttributes -->
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
https://www.youtube.com/watch?v=h7wcvHoxxo0
</div>
</figure>
<!-- /wp:embed -->";
$parsed = parse_blocks($code);
foreach($parsed as $block) {
echo apply_filters('the_content', render_block($block));
}
It's a bit of a faff, but if you need to ensure all the support scripts/styles are loaded (when using the optimised block styles), then you need all the meta tags as well as the actual HTML.
Solved by manually inserting HTML into the template, Thanks.
本文标签: How to render a block from php template
版权声明:本文标题:How to render a block from php template 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736304320a1932193.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论