函数文档

_add_block_template_info()

💡 云策文档标注

概述

_add_block_template_info() 函数用于向模板项添加自定义模板信息,主要基于主题的 theme.json 文件。它检查主题是否包含 theme.json,并从中提取标题和文章类型数据来更新模板项。

关键要点

  • 函数接受一个包含 'slug' 字段的模板项数组作为参数,并返回更新后的模板项。
  • 仅在主题或父主题存在 theme.json 文件时执行信息添加操作。
  • 通过 wp_get_theme_data_custom_templates() 获取自定义模板元数据,并更新模板项的 'title' 和 'postTypes' 字段。
  • 该函数自 WordPress 5.9.0 版本引入,常用于块模板处理流程中。

代码示例

function _add_block_template_info( $template_item ) {
    if ( ! wp_theme_has_theme_json() ) {
        return $template_item;
    }

    $theme_data = wp_get_theme_data_custom_templates();
    if ( isset( $theme_data[ $template_item['slug'] ] ) ) {
        $template_item['title']     = $theme_data[ $template_item['slug'] ]['title'];
        $template_item['postTypes'] = $theme_data[ $template_item['slug'] ]['postTypes'];
    }

    return $template_item;
}

注意事项

  • 函数依赖于 wp_theme_has_theme_json() 和 wp_get_theme_data_custom_templates() 来验证和获取主题数据。
  • 如果模板项的 'slug' 在主题数据中不存在,函数将直接返回原模板项而不做修改。
  • 此函数主要用于内部处理,开发者通常通过更高级的 API 如 get_block_templates() 来访问模板信息。

📄 原文内容

Attempts to add custom template information to the template item.

Parameters

$template_itemarrayrequired
Template to add information to (requires 'slug' field).

Return

array Template item.

Source

function _add_block_template_info( $template_item ) {
	if ( ! wp_theme_has_theme_json() ) {
		return $template_item;
	}

	$theme_data = wp_get_theme_data_custom_templates();
	if ( isset( $theme_data[ $template_item['slug'] ] ) ) {
		$template_item['title']     = $theme_data[ $template_item['slug'] ]['title'];
		$template_item['postTypes'] = $theme_data[ $template_item['slug'] ]['postTypes'];
	}

	return $template_item;
}

Changelog

Version Description
5.9.0 Introduced.