block_template_part()
云策文档标注
概述
block_template_part() 函数用于输出块模板部分,例如页眉或页脚。它基于当前主题的样式表名称和指定部分名称来获取并渲染模板内容。
关键要点
- 函数接受一个必需参数 $part,指定要输出的块模板部分(如 'header' 或 'footer')。
- 内部通过 get_block_template() 获取模板对象,并使用 do_blocks() 解析和输出动态块内容。
- 如果模板不存在或内容为空,函数将静默返回,不输出任何内容。
- 注意:此函数仅输出模板部分的内容,不会应用在块主题中通过 HTML 块模板添加的参数(如 tagName 或 className)。
注意事项
在 PHP 模板中使用 block_template_part() 输出模板部分时,不会包含在块主题中定义的包装元素(如 footer 标签)或 CSS 类(如 site-footer),这可能导致样式或结构差异。
原文内容
Prints a block template part.
Parameters
$partstringrequired-
The block template part to print, for example
'header'or'footer'.
Source
function block_template_part( $part ) {
$template_part = get_block_template( get_stylesheet() . '//' . $part, 'wp_template_part' );
if ( ! $template_part || empty( $template_part->content ) ) {
return;
}
echo do_blocks( $template_part->content );
}
Changelog
| Version | Description |
|---|---|
| 5.9.0 | Introduced. |
Skip to note 2 content
Carolina Nymark
Note that this outputs the content of the template part, and does not use any parameters added to the template part itself.
In other words,
If you have a template part, and you are adding it inside a HTML block template in a block theme with these parameters:
wp:template-part {"slug":"footer","tagName":"footer","className":"site-footer"}Using block_template_part() to output the same template part in a PHP template, does not output the wrapping footer element and the
site-footerCSS class.