How I'm Using LESS CSS with Wordpress

(2012)

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.

functions.php

if( defined( 'DEVELOPMENT' ) ) {
// include less
include('lib/lessphp/lessc.inc.php');
$lessc = new lessc;
$lessc->setPreserveComments(TRUE);

// 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.

functions.php

// ripped off, stolen, borrowed from <a href="http://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files ">http://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files</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 "http://example.com/style.1352475090.css" instead of just "http://example.com/style.css" - 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.