WP-Mix

A fresh mix of code snippets and tutorials

Automatic versioning for enqueued stylesheets

Learn how to append the theme version, random number, or both as a query-string parameter to your CSS stylesheet URLs. This is useful for automatic versioning, cache-busting during development, or both.

1. Get the theme version

Here we use WordPress’ wp_get_theme() to get the theme version (as specified in the theme’s stylesheet, style.css):

// get theme version
function wpmix_get_version() {
	$theme_data = wp_get_theme();
	return $theme_data->Version;
}
$theme_version = wpmix_get_version();
global $theme_version;

No editing required for this step.

2. Get a random number

Next we use a simple PHP function to generate a random number:

// get random number
function wpmix_get_random() {
	$randomizr = '-' . rand(100,999);
	return $randomizr;
}
$random_number = wpmix_get_random();
global $random_number;

The random number may be appended to the URL of stylesheets during development to help encourage browsers to reload the file. Lookup “cache-busting css” for all the gory details.

3. Enqueue CSS

With the version and random numbers now available, we can use them as needed when enqueueing CSS and other files. Here is an example:

// include custom stylesheet
function wpmix_queue_css() {
	global $theme_version, $random_number;
	if (!is_admin()) {
		wp_register_style('custom_styles', get_template_directory_uri() . '/lib/css/custom.css', false, $theme_version . $random_number);
		wp_enqueue_style('custom_styles');
	}
}
add_action('wp_print_styles', 'wpmix_queue_css');

When included via functions.php, the cumulative result of this technique is observable in the source code of your web pages:

<link rel='stylesheet' id='custom_styles-css' href='https://example.com/wp/wp-content/themes/shapeSpace/lib/css/custom.css?ver=1.0-270' type='text/css' media='all' />

Note that all of the codes in this tutorial should be placed into your theme’s functions.php file. Note also that in the enqueue function, you may remove $theme_version, $random_number, or both to display the stylesheet URL as needed.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress