How I'm Using LESS CSS with Wordpress


LESS is pretty cool. It gives you variables and some other handy tricks to make writing stylesheets a bit less tedious. There are a bunch of different ways you could setup a project to use LESS, but here's what I'm doing in Wordpress using the lessphp compiler.


if( defined( 'DEVELOPMENT' ) ) {
// include less
$lessc = new lessc;

// paths for input and target files
$template_directory = get_template_directory();
$stylesheet_in = $template_directory . '/style.less';
$stylesheet_out = $template_directory . '/style.css';

// compile from input file to string of css
$css = $lessc->compile(file_get_contents($stylesheet_in));

// write css to output file
file_put_contents($stylesheet_out, $css);

There are plugins that can do this for you too, but it's pretty easy to just add a few lines to functions.php. If it doesn't work, check the error log and make sure that the style.css file is writeable.

Now, that works great, but you may run into problems with stylesheets getting cached. There are a bunch of different ways to fix this, but my favorite is to change the filename every time you change the file. This can be automated, though the procedure is slightly different for Apache and NGINX.


// ripped off, stolen, borrowed from <a href=" "></a>
function auto_version($file)
// if absolute URL, replace with relative URL
$base = home_url('/');
if(strpos($file, $base) == 0) {
  $file = str_replace($base, '/', $file);

if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) {
  return $file;

$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);

Using that function will give you filenames like "" instead of just "" - convenient cache-busting. Great, so now we just need to tell our webserver to redirect any filenames that look like that to the actual stylesheet:

In Apache, add a rule to .htaccess

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js|jpg|jpeg|png|gif)$ $1.$2 [L]

And with nginx, use this rule instead in your server config:

location / {
rewrite ^(.*)\.[0-9]+\.(css|js|jpg|jpeg|png|gif)$ $1.$2 break;
... etc ...

Note that the snippets are for ALL static content types, but you could easily tweak them to just do CSS. Not sure where I found those last two snippets! But thank you to whoever posted them.