Cache Bust WordPress Assets Based On Git Revision

Cache busting is to rewrite a URL for an asset (JS, CSS, images, etc) so that is unique. This way, you can cache them for as long as you want. If the URL changes, it will use the new file.

I am using deployments tool to checkout the latest version of a given branch, therefore I know that there will be a .git folder on my production server.

The idea is to use the current Git commit as a version number using git head reference.

function project_get_current_git_commit( $branch = 'master', $length = false ) {
  if ( ! defined( 'PROJECT_CURRENT_GIT_COMMIT' ) ) {
    $hash = file_get_contents( sprintf( '%srefs/heads/%s', dirname(__FILE__), $branch ) );

    define( 'PROJECT_CURRENT_GIT_COMMIT', ( $hash ? $hash : false ) );

  return ( $length ? substr( PROJECT_CURRENT_GIT_COMMIT, 0, $length ) : PROJECT_CURRENT_GIT_COMMIT );

// Enqueue WordPress asset
wp_enqueue_script('application','/assets/javascripts/application.min.js', array('), project_get_current_git_commit( 'master', 8 ), true);

Voilá, now you can cache bust everything based upon your latest Git revision.

Of course, there are other ways to do this as well. Another solution is to store environment variables that contains the latest revision and then read it from PHP, that would save some I/O from the physical file.