Last active
April 12, 2019 14:22
-
-
Save nunof07/27305faef26c4e35862c797b8b838232 to your computer and use it in GitHub Desktop.
Generate version identifier for WordPress theme (Sage) using webpack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
npm install --save-dev generate-json-webpack-plugin |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const GenerateJsonPlugin = require('generate-json-webpack-plugin'); | |
// Update your webpack config | |
const webpackConfig = { | |
plugins: [ | |
new GenerateJsonPlugin('version.json', { | |
version: Date.now(), | |
}), | |
], | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assuming Sage theme and webpack build, but this could be adapted to other cases.