I am currently trying to make a customizable Bootstrap theme for my personal WordPress site, however, I am running into some issues.
Bootstrap can be customized by modifying the SCSS variables, and I am trying to bring that customization into the Theme Customizer by utilizing Leafo’s scssphp to recompile Bootstrap on the fly during the use of the Theme Customizer, and then using Minify to downsize it. My current code for that is as follows:
// /wp-content/themes/bootstrap/functions.php
function bootstrap_generate_css() {
require_once(__DIR__ . '/vendor/autoload.php');
$compiler = new Leafo\ScssPhp\Compiler();
$bootstrap_scss = file_get_contents(__DIR__ . '/vendor/twbs/bootstrap/scss/bootstrap.scss');
$compiler->setVariables(array(
'primary' => get_theme_mod('bootstrap_colors_primary', '#007bff')
));
$compiler->setImportPaths(__DIR__ . '/vendor/twbs/bootstrap/scss/');
$css = $compiler->compile($bootstrap_scss);
$minifier = new MatthiasMullie\Minify\CSS($css);
$mincss = $minifier->minify();
file_put_contents(__DIR__ . '/bootstrap.css', $mincss);
}
There doesn’t seem to be a “correct” way to call a function when a setting is changed, either, so I’ve gotten around that by using a sanitizer_callback
:
function bootstrap_sanitize_color($value) {
bootstrap_generate_css();
return($value);
}
This has gotten me to the point that I can customize the colors using the Theme Customizer, however, the changes are not shown in the preview frame, and the changes do not take effect until I have published the theme changes, and then manually re-executed the bootstrap_generate_css()
function.
Because of the size of bootstrap.css
, it is preferable that it is not included into <head>
, and it is furthermore preferable that it is not dynamically generated for every front-end pageview due to the fact that it takes 1.8 seconds to compile for me. I do not mind this delay when making changes in the Theme Customizer.
What would be the “proper” way to store the compiled CSS in WordPress, and also have the changes visible inside of the Theme Customizer preview?