Using WordPress ‘get_file_data()’ PHP function

The get_file_data() WordPress PHP function retrieves metadata from a file, such as a plugin or theme.

Usage

get_file_data( $file, $default_headers, $context = '' )

Example:

$file_path = plugin_dir_path( __DIR__ ) . 'example-plugin-file.php';
$metadata = get_file_data( $file_path, array( 'Version' => 'Version' ) );

Parameters

  • $file (string): Absolute path to the file.
  • $default_headers (array): List of headers, in the format array( 'HeaderKey' => 'Header Name' ).
  • $context (string): Optional. If specified, adds filter hook ‘extra_$context_headers’. Default: ”.

More information

See WordPress Developer Resources: get_file_data

Examples

Registering stylesheet and scripts with plugin version

This example shows how to use the get_file_data() function to read the version number from the main plugin file and use it for enqueuing stylesheets and scripts.

function register_plugin_styles_scripts() {
    $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 );
    }
}

Reading multiple header keys

This example demonstrates how to read multiple header keys using get_file_data().

$filedata = get_file_data( plugin_dir_path(__FILE__) . '/dirName/index.php', array(
    'Page Name' => 'Page Name',
    'Preview Image' => 'Preview Image',
    'Template File' => 'Template File',
));

print_r($filedata);