Skip to content

Instantly share code, notes, and snippets.

@JPry
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPry/9538799 to your computer and use it in GitHub Desktop.
Save JPry/9538799 to your computer and use it in GitHub Desktop.

How to Version a Stylesheet in WordPress

wp_enqueue_style() is your friend

In your theme, you should be using the wp_enqueue_style() function instead of calling your stylesheet directly in your header.php file. Use something like this in your theme's functions.php file:

<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_stylesheet' );
function theme_enqueue_stylesheet() {
	$theme = wp_get_theme();
	wp_enqueue_style( 'theme-style', get_stylesheet_uri(), false, $theme->get( 'Version' ) );
}

How does it work?

The wp_enqueue_scripts hook is where WordPress will print all of your stylesheets and javascript references into your theme's <head> section. When we write add_action( 'wp_enqueue_scripts', 'theme_enqueue_stylesheet' ); we're telling WordPress to include your own customer code along with everything else. That code is contanined in a function named theme_enqueue_stylesheet.

Now that WordPress knows the name of the function to use, we should define that function. That's the next line.

Inside of the function, we first have $theme = wp_get_theme();. We're telling WordPress to retrieve the data about the current theme. Where does that data come from? From the headers of your theme's stylesheet.

Now that we have the theme data, we want to tell WordPress what to do with it. In the next line, we call the wp_enqueue_style() function. Looking at the Codex entry for that function, we can see that the 4th parameter accepted by the function is a version number. This is what we're after! To properly retrieve the theme's version number, we use $theme->get( 'Version' ).

Now what?

Ok, you've done all that, now what? Why does this matter?

Let's say you're making an update to your theme's stylesheet. Normally, your browser will cache the stylesheet, which means that you have to manually refresh the page in your browser to get the new version. This is tedious for you, and it's also no good for your visitors, because how do they know that they even need to refresh? That's where the versioning comes in.

Now that your stylesheet is versioned, your browser can still cache the stylesheet, but now it has a version to go with it. If you make a change to your stylesheet, then you should update the version (which conveniently, also lives in the stylesheet) at the same time. Now your new styles are immediately available without any refreshing needed!

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