_remove_theme_attribute_in_block_template_content()
云策文档标注
概述
此函数用于解析块模板内容,移除每个模板部分中的 theme 属性。它已被弃用,建议使用替代方法。
关键要点
- 函数 _remove_theme_attribute_in_block_template_content() 解析序列化的块模板内容,移除所有 core/template-part 块中的 theme 属性。
- 从 WordPress 6.4.0 版本起,此函数被弃用,推荐使用 traverse_and_serialize_blocks( parse_blocks( $template_content ), "_remove_theme_attribute_from_template_part_block" ) 作为替代。
- 函数内部使用 parse_blocks() 解析块,_flatten_blocks() 扁平化块结构,serialize_block() 序列化块以返回更新后的内容。
代码示例
function _remove_theme_attribute_in_block_template_content( $template_content ) {
_deprecated_function(
__FUNCTION__,
'6.4.0',
'traverse_and_serialize_blocks( parse_blocks( $template_content ), "_remove_theme_attribute_from_template_part_block" )'
);
$has_updated_content = false;
$new_content = '';
$template_blocks = parse_blocks( $template_content );
$blocks = _flatten_blocks( $template_blocks );
foreach ( $blocks as $key => $block ) {
if ( 'core/template-part' === $block['blockName'] && isset( $block['attrs']['theme'] ) ) {
unset( $blocks[ $key ]['attrs']['theme'] );
$has_updated_content = true;
}
}
if ( ! $has_updated_content ) {
return $template_content;
}
foreach ( $template_blocks as $block ) {
$new_content .= serialize_block( $block );
}
return $new_content;
}注意事项
- 此函数自 WordPress 6.4.0 起被弃用,新代码应避免使用,改用推荐的替代方法。
- 函数仅处理 core/template-part 块,其他块类型不受影响。
- 如果模板内容中没有 theme 属性可移除,函数将直接返回原始内容。
原文内容
Parses a block template and removes the theme attribute from each template part.
Parameters
$template_contentstringrequired-
Serialized block template content.
Source
function _remove_theme_attribute_in_block_template_content( $template_content ) {
_deprecated_function(
__FUNCTION__,
'6.4.0',
'traverse_and_serialize_blocks( parse_blocks( $template_content ), "_remove_theme_attribute_from_template_part_block" )'
);
$has_updated_content = false;
$new_content = '';
$template_blocks = parse_blocks( $template_content );
$blocks = _flatten_blocks( $template_blocks );
foreach ( $blocks as $key => $block ) {
if ( 'core/template-part' === $block['blockName'] && isset( $block['attrs']['theme'] ) ) {
unset( $blocks[ $key ]['attrs']['theme'] );
$has_updated_content = true;
}
}
if ( ! $has_updated_content ) {
return $template_content;
}
foreach ( $template_blocks as $block ) {
$new_content .= serialize_block( $block );
}
return $new_content;
}