- CSS
- JavaScript
- PHP
- WordPress
This is mainly for use in WordPress, when registering and enqueuing styles and scripts (using wp_register_style() and wp_register_script() ), but in theory you can use this in any PHP application. This code will look at the last modified date of the passed in file path and then appends this to the URL output in the source code;
// force version for CSS and JS - change the file paths where needed
$css_ver = date("Ymd-His", filemtime( get_theme_file_path() . '/css/style.css'));
$js_ver = date("Ymd-His", filemtime( get_theme_file_path() . '/js/min/scripts-min.js'));
wp_register_style( 'load-css', get_stylesheet_directory_uri().'/css/style.css', array(), $css_ver, 'all' );
wp_enqueue_style( 'load-css' );
The above will get the file paths from the active WordPress theme, but you can pass any valid file path into the filemtime() function.
Remember too, that you should always add wp_register_style()
and wp_enqueue_style()
within a add_action()
block, as follows:
add_action( 'wp_enqueue_scripts', 'td_register_styles' );
function td_register_styles() {
// wp_register_style()
// wp_enqueue_style()
}
The results of this will be something like the following:
<link rel='stylesheet' id='main-style-css' href='https://tobydawes.com/[path-to-theme]/css/style.css?ver=20230812-212342' type='text/css' media='screen' />