Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

In terms of best practices, I'm curious as to why I haven't seen anyone using get_file_data or get_plugin_data to handle getting a plugin version (for versioning CSS/JS files). Many quality plugins do version their files, but they hard code the version number, which strikes me as prone to being missed at release time.

Obviously these functions have a bit of an overhead since we're doing file IO rather than just having the version, but this seems like a small price to pay for one less easy mistake in releases.

A function like the following seems much more reasonable than hard coding, so why isn't it used? I presume there is a good reason, but I'm not seeing it.

 public static function version() {
   static $version = false;
   if(false === $version) {
      include_once WP_ADMIN_DIR . '/includes/plugin.php';
      $data = get_plugin_data(__FILE__, false);
      $version = $data['Version'];
   }

   return $version;
}
share|improve this question
    
How can we know why you haven’t seen that? I do that sometimes, sometimes not. –  toscho Mar 9 at 17:42
    
You can know because I'm saying that I haven't. I'm sure some do, but nowhere in the Codex is this method used and I've read a number of plugins over the years, none of which has used it. The question is completely valid, especially since it is explicitly asking for information on best practices. –  Dan Mar 9 at 17:44

1 Answer 1

up vote 1 down vote accepted

I don't think it is possible to answer the question directly. I don't know why you haven't seen similar code and I don't know why plugin authors do or don't use similar code. However...

The functions you mention locate, read, and process a file. It is going to be quicker and easier, both writing the code and (probably) executing it, to use a constant to hold the version number than it is to locate, read, and process a file from the filesystem.

You are correct that this means that there are two version numbers to watch for but I can't get past the profligacy, in my head anyway, of a plugin reading its own file to find out what version it is. PHP doesn't compile into an executable so that has to happen on every page load where the version is needed. The details of the implementation could make that a moot point, but in general I would shy away from it.

On the other hand, if a plugin or a theme needed to find data about some other plugin, the functions you mention would be spot on. That is the use case for those functions, in my opinion.

share|improve this answer
    
That works for me. Thanks! –  Dan Mar 9 at 18:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.