函数文档

wp_get_theme_data_template_parts()

💡 云策文档标注

概述

wp_get_theme_data_template_parts() 函数用于获取主题定义的模板部分的元数据。它返回一个关联数组,包含模板部分的名称和详细信息,并利用缓存机制优化性能。

关键要点

  • 函数返回一个关联数组,键为模板部分名称,值为包含 "title" 和 "area" 字段的数据。
  • 实现中使用了缓存机制,通过 wp_cache_get() 和 wp_cache_set() 提高效率,但仅在非主题开发模式下启用缓存。
  • 核心逻辑依赖于 WP_Theme_JSON_Resolver::get_theme_data() 来获取主题数据并提取模板部分信息。
  • 该函数自 WordPress 6.4.0 版本引入。

代码示例

function wp_get_theme_data_template_parts() {
    $cache_group    = 'theme_json';
    $cache_key      = 'wp_get_theme_data_template_parts';
    $can_use_cached = ! wp_is_development_mode( 'theme' );

    if ( $can_use_cached ) {
        $metadata = wp_cache_get( $cache_key, $cache_group );
        if ( false !== $metadata ) {
            return $metadata;
        }
    }

    $metadata = WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_template_parts();
    if ( $can_use_cached ) {
        wp_cache_set( $cache_key, $metadata, $cache_group );
    }

    return $metadata;
}

注意事项

  • 缓存仅在 wp_is_development_mode( 'theme' ) 返回 false 时生效,确保在主题开发模式下能获取最新数据。
  • 返回的元数据格式固定,包含 "title" 和 "area" 字段,开发者需按此结构处理数据。

📄 原文内容

Returns the metadata for the template parts defined by the theme.

Return

array Associative array of $part_name => $part_data pairs, with $part_data having “title” and “area” fields.

Source

function wp_get_theme_data_template_parts() {
	$cache_group    = 'theme_json';
	$cache_key      = 'wp_get_theme_data_template_parts';
	$can_use_cached = ! wp_is_development_mode( 'theme' );

	if ( $can_use_cached ) {
		$metadata = wp_cache_get( $cache_key, $cache_group );
		if ( false !== $metadata ) {
			return $metadata;
		}
	}

	$metadata = WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_template_parts();
	if ( $can_use_cached ) {
		wp_cache_set( $cache_key, $metadata, $cache_group );
	}

	return $metadata;
}

Changelog

Version Description
6.4.0 Introduced.