Compiling assets

The Beans Compiler API can be used to compile multiple internal or external CSS, LESS and JS files on a per page basis. LESS content is automatically processed to CSS.

All compiled files are cached and stored in a shared folder (‘wp-content/uploads/beans/compiler/’ by default), which makes it easy to flush your assets cache, via the Admin->Appearance->Settings->Flush Assets Cache setting. New compiled files are re-created on the fly.

The Beans Compiler will also detect changes to your asset files and recompile them on the fly. This is a great feature while working on a site, espcially when working with LESS files.

This feature should only be used while in your site is in development and as such, needs to be enabled in your WordPress Admin->Appearance->Settings.

Using the Compiler

The assets compiling and enqueueing works in a similar fashion as the Core WordPress assets enqueueing. Therefore, all compiling functions must be called using the wp_enqueue_scripts action hook.

CSS files are compiled using beans_compile_css_fragments(), LESS files using beans_compile_less_fragments() and JS files using beans_compile_js_fragments().

It is also important to note that compiled assets are automatically enqueued using the WordPress enqueueing functions.

add_action( 'wp_enqueue_scripts', 'my_function_name' );

function my_function_name() {

  beans_compile_css_fragments( 'css_compiler_id', array( 'file_path', 'file_path' ) );
  beans_compile_less_fragments( 'less_compiler_id', array( 'file_path', 'file_path' ) );
  beans_compile_js_fragments( 'js_compiler_id', array( 'file_path', 'file_path' ) );

}

Here’s how it would look in the front end:

<link rel="stylesheet" id="css-compiler-id-css" href="http://domain.com/uploads/beans/compiler/css-compiler-id/cb5d374.css?ver=4.2.2" type="text/css" media="all">
<link rel="stylesheet" id="less-compiler-id-css" href="http://domain.com/uploads/beans/compiler/less-compiler-id/7547706.css?ver=4.2.2" type="text/css" media="all">
<script type="text/javascript" src="http://domain.com/uploads/beans/compiler/js-compiler-id/dd834f2.js?ver=4.2.2"></script>

To take it further, all enqueued assests can then be compiled into one file.

Adding fragments to an existing instance of the compiler

Assets files can be added to an existing instance of the compiler, via a child theme or plugin using beans_compiler_add_fragment().

This is especially usefull when LESS variables need to be accessible in a fragment file.

The example below adds a fragment file to the less_compiler_id, that we added earlier.

add_action( 'wp_enqueue_scripts', 'my_function_name' );

function my_function_name() {

 beans_compiler_add_fragment( 'less_compiler_id', 'fragment_file_path' );

}