函数文档

get_file_data()

💡 云策文档标注

概述

get_file_data() 函数用于从文件(如插件或主题)中提取元数据,仅搜索文件前 8 KB 的内容。元数据必须每行一个字段,不支持跨行。

关键要点

  • 函数从指定文件的绝对路径中读取元数据,元数据需位于文件前 8 KB 内,否则开发者应调整文件头部位置。
  • 参数包括:$file(文件路径,字符串,必需)、$default_headers(头部数组,必需,格式为 array('HeaderKey' => 'HeaderName'))、$context(上下文,字符串,可选,用于添加过滤器钩子)。
  • 返回值为字符串数组,键为头部名称,值为对应的头部值。
  • 函数内部使用 file_get_contents 读取前 8 KB 数据,处理换行符,并通过 apply_filters 支持动态添加额外头部。
  • 相关函数包括 get_plugin_data()、WP_Theme 类方法等,用于插件和主题的元数据解析。

代码示例

// 示例:从插件文件读取版本号并用于样式和脚本版本控制
$file_path = plugin_dir_path( __DIR__ ) . 'example-plugin-file.php';
$plugin_data = get_file_data( $file_path, array(
    'Version' => 'Version'
) );
if ( ! empty( $plugin_data['Version'] ) ) {
    $ver = $plugin_data['Version'];
    wp_enqueue_style( 'public-style', plugins_url( 'path/to/stylesheet.css' ), array(), $ver );
    wp_enqueue_script('public-script', plugins_url( 'path/to/script.js' ), array(), $ver , true);
}

注意事项

  • 元数据字段必须每行独立,不支持跨行,否则值会被截断在第一行末尾。
  • 如果元数据不在文件前 8 KB 内,函数可能无法正确读取,开发者需确保头部位于文件顶部。
  • 使用 $context 参数可以添加过滤器钩子 'extra_{$context}_headers',以动态扩展头部列表。

📄 原文内容

Retrieves metadata from a file.

Description

Searches for metadata in the first 8 KB of a file, such as a plugin or theme.
Each piece of metadata must be on its own line. Fields can not span multiple lines, the value will get cut at the end of the first line.

If the file data is not within that first 8 KB, then the author should correct their plugin file and move the data headers to the top.

Parameters

$filestringrequired
Absolute path to the file.
$default_headersarrayrequired
List of headers, in the format array( 'HeaderKey' => 'Header Name' ).
$contextstringoptional
If specified adds filter hook ‘extra_$context_headers’.
Default empty string.

Return

string[] Array of file header values keyed by header name.

Source

function get_file_data( $file, $default_headers, $context = '' ) {
	// Pull only the first 8 KB of the file in.
	$file_data = file_get_contents( $file, false, null, 0, 8 * KB_IN_BYTES );

	if ( false === $file_data ) {
		$file_data = '';
	}

	// Make sure we catch CR-only line endings.
	$file_data = str_replace( "r", "n", $file_data );

	/**
	 * Filters extra file headers by context.
	 *
	 * The dynamic portion of the hook name, `$context`, refers to
	 * the context where extra headers might be loaded.
	 *
	 * @since 2.9.0
	 *
	 * @param array $extra_context_headers Empty array by default.
	 */
	$extra_headers = $context ? apply_filters( "extra_{$context}_headers", array() ) : array();
	if ( $extra_headers ) {
		$extra_headers = array_combine( $extra_headers, $extra_headers ); // Keys equal values.
		$all_headers   = array_merge( $extra_headers, (array) $default_headers );
	} else {
		$all_headers = $default_headers;
	}

	foreach ( $all_headers as $field => $regex ) {
		if ( preg_match( '/^(?:[ t]*<?php)?[ t/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] ) {
			$all_headers[ $field ] = _cleanup_header_comment( $match[1] );
		} else {
			$all_headers[ $field ] = '';
		}
	}

	return $all_headers;
}

Hooks

apply_filters( “extra_{$context}_headers”, array $extra_context_headers )

Filters extra file headers by context.

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    /**
     * Register stylesheet and scripts
     * Set the version of each the version of the plugin. 
     */
    function register_plugin_styles_scripts() {
    	// Set the file path to a variable.
    	$file_path = plugin_dir_path( __DIR__ ) . 'example-plugin-file.php';
    	// Read the version number from the main plugin file then set it to a variable.
    	$plugin_data = get_file_data( $file_path, array(
    		'Version' => 'Version'
    	) );
    
    	if ( ! empty( $plugin_data['Version'] ) ) {
    		// The the value of the Version header to a variable.
    		$ver = $plugin_data['Version'];
    
    		// Use the variable, $ver, in more than one stylesheet/script to bust cache when the plugin gets updated.
    		wp_enqueue_style( 'public-style', plugins_url( 'path/to/stylesheet.css' ), array(), $ver );
    		wp_enqueue_script('public-script', plugins_url( 'path/to/script.js' ), array(), $ver , true);
    	}
    }