Skip to content

Instantly share code, notes, and snippets.

@JPry
Last active September 23, 2015 21:10
Show Gist options
  • Save JPry/49f26495b5f2a4a702bb to your computer and use it in GitHub Desktop.
Save JPry/49f26495b5f2a4a702bb to your computer and use it in GitHub Desktop.

get_file_data() Plugin example

Problem

You need to know the version of your plugin in your code. How do you do that? Maybe a constant, maybe a hard-coded string somewhere. Whichever way you go, you have at least 2 places where the plugin version lives: your hard-coded string/constant/whatever, and the plugin header used by WordPress. Updating things in more than one place is a pain.

Solution

Use the get_file_data() function to retrieve information about your plugin. Then use that in your code instead of hard-coding the value. BAM, only one place to update the version.

Why not use get_plugin_data() instead?

That function is only loaded inside the /wp-admin/ section of the dashboard, while get_file_data() is loaded everywhere.

<?php
/**
* Plugin Name: File Data Sample
* Plugin URI: https://gist.github.com/JPry/49f26495b5f2a4a702bb
* Version: 0.1.0
* Description: A fun example of get_file_data() for a single location of a version.
* Author: JPry
*/
class JPry_File_Data_Plugin {
/**
* The transient key.
*
* @var string
*/
protected $transient_key = 'jpry_file_data_plugin_version';
/**
* The plugin version.
*
* @var string
*/
protected $version = '';
/**
* Constructor.
*/
public function __construct() {
$this->setup_version();
}
/**
* Get the plugin version.
*
* @return string The plugin version.
*/
public function get_version() {
return $this->version;
}
/**
* Retrieve the file version info from a transient.
*
* We store it in a transient because file reads can be heavy. This way we keep those to a minimum.
*/
private function setup_version() {
$version = get_transient( $this->transient_key );
// Set up the version if the transient is missing.
if ( false === $version ) {
// These are the headers you care about looking up.
$headers = array(
'version' => 'Version',
);
// Grab the data
$data = get_file_data( __FILE__, $headers );
$version = $data['version'];
// Store the transient for a week
set_transient( $this->transient_key, $version, WEEK_IN_SECONDS );
}
$this->version = $version;
}
}
$instance = new JPry_File_Data_Plugin();
// This will echo "0.1.0"
echo $instance->get_version();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment