函数文档

_inject_theme_attribute_in_block_template_content()

💡 云策文档标注

概述

此函数用于解析 wp_template 内容,并为每个 wp_template_part 块注入当前活动主题的样式表作为 theme 属性。自 WordPress 6.4.0 起已弃用,建议使用替代方法。

关键要点

  • 函数 _inject_theme_attribute_in_block_template_content() 处理序列化的 wp_template 内容,返回更新后的内容字符串。
  • 它遍历块结构,为未设置 theme 属性的 core/template-part 块添加 theme 属性,值为 get_stylesheet()。
  • 自 6.4.0 版本起,此函数被标记为弃用,推荐使用 traverse_and_serialize_blocks( parse_blocks( $template_content ), "_inject_theme_attribute_in_template_part_block" ) 替代。

代码示例

function _inject_theme_attribute_in_block_template_content( $template_content ) {
    _deprecated_function(
        __FUNCTION__,
        '6.4.0',
        'traverse_and_serialize_blocks( parse_blocks( $template_content ), "_inject_theme_attribute_in_template_part_block" )'
    );

    $has_updated_content = false;
    $new_content         = '';
    $template_blocks     = parse_blocks( $template_content );

    $blocks = _flatten_blocks( $template_blocks );
    foreach ( $blocks as &$block ) {
        if (
            'core/template-part' === $block['blockName'] &&
            ! isset( $block['attrs']['theme'] )
        ) {
            $block['attrs']['theme'] = get_stylesheet();
            $has_updated_content     = true;
        }
    }

    if ( $has_updated_content ) {
        foreach ( $template_blocks as &$block ) {
            $new_content .= serialize_block( $block );
        }

        return $new_content;
    }

    return $template_content;
}

注意事项

  • 此函数已弃用,开发者应避免在新代码中使用,并迁移到推荐的替代方案。
  • 相关函数包括 _flatten_blocks(), serialize_block(), parse_blocks(), get_stylesheet(), 和 _deprecated_function(),用于块处理和主题属性注入。

📄 原文内容

Parses wp_template content and injects the active theme’s stylesheet as a theme attribute into each wp_template_part

Parameters

$template_contentstringrequired
serialized wp_template content.

Return

string Updated 'wp_template' content.

Source

function _inject_theme_attribute_in_block_template_content( $template_content ) {
	_deprecated_function(
		__FUNCTION__,
		'6.4.0',
		'traverse_and_serialize_blocks( parse_blocks( $template_content ), "_inject_theme_attribute_in_template_part_block" )'
	);

	$has_updated_content = false;
	$new_content         = '';
	$template_blocks     = parse_blocks( $template_content );

	$blocks = _flatten_blocks( $template_blocks );
	foreach ( $blocks as &$block ) {
		if (
			'core/template-part' === $block['blockName'] &&
			! isset( $block['attrs']['theme'] )
		) {
			$block['attrs']['theme'] = get_stylesheet();
			$has_updated_content     = true;
		}
	}

	if ( $has_updated_content ) {
		foreach ( $template_blocks as &$block ) {
			$new_content .= serialize_block( $block );
		}

		return $new_content;
	}

	return $template_content;
}

Changelog

Version Description
6.4.0 Deprecated. Use traverse_and_serialize_blocks( parse_blocks( $template_content ), '_inject_theme_attribute_in_template_part_block' ) instead.
5.9.0 Introduced.