Skip to content

Instantly share code, notes, and snippets.

@nunof07

nunof07/functions.php

Last active Apr 12, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@nunof07 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