_inject_theme_attribute_in_block_template_content

函式
_inject_theme_attribute_in_block_template_content ( $template_content )
Access
Private
引數
  • (string) $template_content serialized wp_template content.
    Required:
返回值
  • (string) Updated 'wp_template' content.
定義位置
相關方法
_remove_theme_attribute_in_block_template_contentget_default_block_template_typesget_the_block_template_htmlget_theme_starter_content_register_theme_block_patterns
引入
5.9.0
棄用
-

inject_theme_attribute_in_block_template_content是一個WordPress函式,用於將主題屬性注入到塊模板的內容中: 這是通過解析區塊模板的HTML內容並根據其型別為某些元素新增屬性來實現的。例如,如果區塊模板包含一個影象元素,該函式可能會給該元素新增一個”data-theme-url”屬性,其值指向當前主題的目錄: 這個函式在區塊編輯器中使用,允許主題提供自定義區塊模板,包括主題特定的功能。

解析wp_template內容,並將活動主題的樣式表作為主題屬性注入每個wp_template_part中。

function _inject_theme_attribute_in_block_template_content( $template_content ) {
	$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'] = wp_get_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;
}

常見問題

FAQs
檢視更多 >