[更新我在@S.Walsh 回答后添加了更多细节,因为我仍然停留在如何在内容区域中进行 include_once 渲染。]
我的自定义插件包括一个使用 PHP 函数作为其“render_callback”的 Gutenberg 动态块。我希望这个渲染函数做一些类似于 PHP include_once() 的事情来包含一个模板部分。
我可以使用 get_template_part,但是我如何告诉 Wordpress 只执行一次,尽管该块被使用了多少次(类似于 PHP include_once)?
我的 block.php 看起来像这样:
register_block_type( __DIR__ . '/build/chart', [
'render_callback' => 'chart_render',
'attributes' => [
'theFile' => [
'type' => 'string',
'default' => ''
],
'theVars' => [
'type' => 'string',
'default' => ''
]
]
] );
渲染函数的输出部分如下所示:
function chart_render($attr, $content) {
ob_start();
get_template_part($path_to_template_part, null);
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
我想包含另一个为图表提供支持的单独 PHP 文件,但我只想包含它一次,无论我的块在页面/帖子中使用了多少次。这就是我卡住的地方。
我可以简单地将 include_once() 添加到渲染函数,但文件的内容在帖子内容加载之前渲染。换句话说,我尝试包含的文件在前端 HTML 标记上方获取输出。我希望它与块所在的帖子内容一起呈现。
function my_dependencies () {
if(has_blocks('chart')) {
include_once (my_path/myfile.php' );
}
}
add_action( 'init', 'my_dependencies' );
如果我把那个函数放在 block.php 中,它总是会返回 false。我怀疑内容块在注册时不存在。如果我将该函数放在渲染函数调用的模板部分中,那么它将在标记之前渲染内容。
不相关,但你可能会问我为什么要这样做?我有一个专门的主题,允许我的内容编辑器选择要在帖子中加载的某些图表,以及用户提供的一系列参数。这些图表依赖于一个单独的 PHP 文件,该文件只需要在帖子中出现一次(不是每个区块一次)。
Output buffering 可用于将您的其他 PHP 模板文件包含在动态块的render_callback
中。
基于更新问题的更新示例
你的
动态块有两个属性,“theFile”和“theVars”有一个安全的默认值''
,这是一个很好的做法。 PHP 模板包含一个根据保存的块属性返回图表内容的函数。当在
render_callback
中调用时,输出缓冲
include_once()
文件的内容不会在块之前打印:
template.php
<?php
function render_chart($file, $vars)
{
// return chart content or other dynamic content
return "<p>File: ".$file."Vars: ".$vars."</p>";
}
plugin.php
<?php
function chart_render($attrs, $content)
{
include_once 'src/template.php';
// Start the output buffer
ob_start();
// Print the block wrapper attributes (classnames etc)
echo "<div " . get_block_wrapper_attributes() . ">";
// Include once the "template.php" file when the block rendered with
// $block_attributes passed to render_chart() function of the template
echo render_chart($attrs['theFile'], $attrs['theVars']);
// Print closing block tag
echo "</div>";
// Get the output buffer content to return
$content = ob_get_clean();
// End the output buffer
ob_flush();
// Returns the content ready to render
return $content;
}
NB. 请记住 PHP 中 require 与 include 之间的区别。使用 require()
将抛出致命错误并停止脚本