As a web designer for local businesses, I create my clients websites almost exclusively in WordPress. Sometime in the last six months I stated using LESS as a preprocessor for my CSS files. Although LESS has made my theme development much more efficient, it took me awhile to discover the best way to integrate it into my workflow. I wanted my LESS to compile automatically. Although the final solution is fairly straitforward, it took me quite a while to gather all the information I needed to figure out the best way to do this.
The first step is to use lessphp, a LESS compiler for PHP, to automatically compile my stylesheets. To do this I first had to download lessphp and put lessc.inc.php and lessify.inc.php in a /less directory inside my theme directory. I then include the following code at the top of my theme’s header.php file (right below the opening <?php tag):
include_once 'less/lessc.inc.php'; $less = new lessc(dirname(__FILE__).'/less/styles.less'); $stylesheet = '/* Theme Name: Theme Name Theme URI: http://www.mywebsite.com/ Description: Theme Description. Version: 1.0 Author: Author Name Author URI: http://www.mywebsite.com/ */ '.$less->parse(); file_put_contents(dirname(__FILE__).'/style.css', $stylesheet);
This code begins by importing lessphp and reading my main less file. WordPress uses comments in the main stylesheet to identify theme information. One feature of LESS is minification, which includes the removal of comments. Unfortunately, this also removes these important comments needed by WordPress. Fortunately, it is easy to prepend this information to our newly compiled LESS file, before writing it to style.css in the theme’s main directory.
At this point we have a working solution for automatically compiling our LESS files. Any changes to my main LESS file will be automatically compiled everytime I load a page. We are still missing one thing though; my stylesheets do not automatically reload everytime I make a change. Because our LESS is being compiled by PHP when the page is loaded, a solution like Live Reload isn’t going to work. So, what is the solution?
Then at the top of header.php I insert (right below the earlier lessphp code):
$dev = true; //Set to false when site is ready to deploy!
When $dev is set to true WordPress will use less.js and watch for changes in my LESS file. When my site is ready to go live I simply set $dev to false and WordPress starts using lessphp instead!
Looking for a WordPress developer? Contact Nose Creek Web Design today!