我将描述我最近在一个有类似需求的项目上所做的工作。
我做的第一件事就是打包less.php 在我的主题中创建一个函数来编译。将主题中的较少文件转换为CSS并返回结果。看起来是这样的:
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;
}
在我的主题中
customizer.less 其中包括我要自定义的所有选择器和规则
@ 我想要自定义值的地方的变量更少。对于上面的示例,它可能看起来像:
body {
color: @primaryColor;
}
在此函数中
ModifyVars 设置变量值的方式与JS示例类似,但没有
@. 这是您检索要填充的值的地方。就我而言,他们只是打电话给
get_theme_mod(), 但在你的
WPEdenThemeEngine. 没什么大不了的。
下一步是创建一个钩子来保存已编译的CSS,这样我就不需要在每次加载页面时生成它。在我的例子中,我使用的是来自定制器的值,所以我使用customize_save_after 并将结果保存到新的主题模型中,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\' );
然后我需要在
<head> 使用
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 );
这将加载
get_theme_mod( \'css\' ), 我保存的CSS,放入
<head> 但请注意,我检查了
is_customize_preview(). 因为我使用的是自定义程序值,所以我希望在更改自定义程序中的值时更新预览。
因为自定义程序控件不会触发customize_save_after 更改后,我需要在每次加载页面时编译CSS,因此如果is_customize_preview() 是真的,我只是跑wpse_283711_get_customizer_css() 不保存结果,直接执行。您不希望每次实际页面加载都少解析,这就是为什么我保存到主题模块,但这对于预览更改是必要的。如果您没有使用Customizer,这可能与您无关。