函数文档

wp_get_block_name_from_theme_json_path()

💡 云策文档标注

概述

wp_get_block_name_from_theme_json_path() 函数用于从给定的 theme.json 路径数组中提取块名称。它通过解析路径数组来识别块名称,支持标准路径格式和向后兼容性。

关键要点

  • 参数 $path 是一个数组,描述 theme.json 中属性的路径。
  • 返回值为字符串,表示识别的块名称;如果未找到,则返回空字符串。
  • 函数优先检查路径数组的前三个元素是否为 'styles'、'blocks' 和包含 '/' 的块名称。
  • 作为回退机制,函数会过滤路径数组中包含 'core/' 的元素,以支持向后兼容性。

代码示例

function wp_get_block_name_from_theme_json_path( $path ) {
    // Block name is expected to be the third item after 'styles' and 'blocks'.
    if (
        count( $path ) >= 3
        && 'styles' === $path[0]
        && 'blocks' === $path[1]
        && str_contains( $path[2], '/' )
    ) {
        return $path[2];
    }

    /*
     * As fallback and for backward compatibility, allow any core block to be
     * at any position.
     */
    $result = array_values(
        array_filter(
            $path,
            static function ( $item ) {
                if ( str_contains( $item, 'core/' ) ) {
                    return true;
                }
                return false;
            }
        )
    );
    if ( isset( $result[0] ) ) {
        return $result[0];
    }
    return '';
}

📄 原文内容

Gets the block name from a given theme.json path.

Parameters

$patharrayrequired
An array of keys describing the path to a property in theme.json.

Return

string Identified block name, or empty string if none found.

Source

function wp_get_block_name_from_theme_json_path( $path ) {
	// Block name is expected to be the third item after 'styles' and 'blocks'.
	if (
		count( $path ) >= 3
		&& 'styles' === $path[0]
		&& 'blocks' === $path[1]
		&& str_contains( $path[2], '/' )
	) {
		return $path[2];
	}

	/*
	 * As fallback and for backward compatibility, allow any core block to be
	 * at any position.
	 */
	$result = array_values(
		array_filter(
			$path,
			static function ( $item ) {
				if ( str_contains( $item, 'core/' ) ) {
					return true;
				}
				return false;
			}
		)
	);
	if ( isset( $result[0] ) ) {
		return $result[0];
	}
	return '';
}

Changelog

Version Description
6.3.0 Introduced.