Why haven’t I see plugins using get_file_data to handle retrieving plugin version?

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;
}

Answer

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.

Attribution
Source : Link , Question Author : Dan , Answer Author : s_ha_dum

Leave a Comment