Skip to content

Instantly share code, notes, and snippets.

@nunof07
Last active April 12, 2019 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nunof07/27305faef26c4e35862c797b8b838232 to your computer and use it in GitHub Desktop.
Save nunof07/27305faef26c4e35862c797b8b838232 to your computer and use it in GitHub Desktop.
Generate version identifier for WordPress theme (Sage) using webpack
<?php
/**
* Theme version string.
* Tries to read a "version.json" file in the "dist" folder - a JSON file with a "version" property.
* If this file is not available it returns the WordPress version.
*
* @return string
*/
function theme_version()
{
$version = get_bloginfo('version');
$version_json_path = get_template_directory() . '/../dist/version.json';
if (file_exists($version_json_path)) {
$version_json = file_get_contents($version_json_path);
if (!empty($version_json)) {
$version_json_data = json_decode($version_json);
if (!empty($version_json_data)) {
if (!empty($version_json_data->version)) {
$version = $version_json_data->version;
}
}
}
}
return $version;
}
/**
* Theme assets
*/
add_action('wp_enqueue_scripts', function () {
$version = theme_version();
wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, $version);
wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], $version, true);
if (is_single() && comments_open() && get_option('thread_comments')) {
wp_enqueue_script('comment-reply');
}
}, 100);
npm install --save-dev generate-json-webpack-plugin
const GenerateJsonPlugin = require('generate-json-webpack-plugin');
// Update your webpack config
const webpackConfig = {
plugins: [
new GenerateJsonPlugin('version.json', {
version: Date.now(),
}),
],
};
@nunof07
Copy link
Author

nunof07 commented Apr 5, 2019

Assuming Sage theme and webpack build, but this could be adapted to other cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment