WordPress Theme customisation CSS

I’ll describe what I did on a project recently that had similar requirements.

First thing I did was bundle less.php in my theme and create a function to compile a .less file in my theme into CSS and return the result. It looked like this:

function wpse_283711_get_customizer_css() {
    $css="";

    if ( file_exists( get_theme_file_path( 'customizer.less' ) ) ) {
        require_once get_parent_theme_file_path( '/lib/less.php/Less.php' );

        $less = new Less_Parser;

        $less->parseFile( get_theme_file_path( 'customizer.less' ) );

        $less->ModifyVars( array(
            'primaryColor' => get_theme_mod( 'primary_color' ),
        ) );

        $css = $less->getCss();
    }

    return $css;
}

In my theme I have customizer.less which includes all the selectors and rules that I want to customize, with @ less variables for where I want my custom values. For the above example, it might look like:

body {
    color: @primaryColor;
}

In this function ModifyVars sets the variable values similarly to how your JS example does, but without the @. This is where you’re retrieve the values you want to populate with. In my case they were just calls to get_theme_mod(), but in yours you’d be using WPEdenThemeEngine. Doesn’t really matter.

Next this is to create a hook that will save the compiled CSS, so that I don’t need to generate it on each page load. In my case I’m using values from the Customizer so I used customize_save_after and saved the result into a new theme mod, css.

function wpse_283711_save_customizer_css() {
    set_theme_mod( 'css', wpse_283711_get_customizer_css() );
}
add_action( 'customize_save_after', 'wpse_283711_save_customizer_css' );

Then I need to output the custom CSS in the <head> using wp_add_inline_style().

function wpse_283711_enqueue_customizer_css() {
    $css="";

    if ( is_customize_preview() ) {
        $css = wpse_283711_get_customizer_css();
    } elseif ( get_theme_mod( 'css' ) ) {
        $css = get_theme_mod( 'css' );
    }

    wp_add_inline_style( 'stylesheet-handle', $css );
}
add_action( 'wp_enqueue_scripts', 'wpse_283711_enqueue_customizer_css', 11 );

This will load the value of get_theme_mod( 'css' ), my saved CSS, into the <head> of the site, but notice that I check is_customize_preview(). Since I’m using customizer values, I want the preview to update when I change values in the Customizer.

Since Customizer controls don’t trigger customize_save_after when changed, I need to compile the CSS each time the page loads, so if is_customize_preview() is true, I just run wpse_283711_get_customizer_css() directly without saving the result. You won’t want parse LESS every real page load, which is why I save to a theme mod, but it’s necessary for previewing changes. If you’re not using the Customizer, this probably isn’t relevant to you.

Leave a Comment