对这可以通过创建自定义选择性刷新来实现Partial
类型,并重写refresh
方法。
下面是相关的JavaScript,它应该在Customizer预览中排队,使用customize-selective-refresh
作为其脚本依赖项:
wp.customize.selectiveRefresh.partialConstructor.body_class = wp.customize.selectiveRefresh.Partial.extend({
/**
* Class name choices.
*
* This is populated in PHP via `wp_add_inline_script()`.
*
* @type {Array}
*/
choices: [],
/**
* Refresh partial.
*
* Override refresh behavior to bypass partial refresh request in favor of direct DOM manipulation.
*
* @returns {jQuery.Promise} Resolved promise.
*/
refresh: function() {
var partial = this, setting, body, deferred, className;
setting = wp.customize( partial.params.primarySetting );
className = setting.get();
body = $( document.body );
body.removeClass( partial.choices.join( \' \' ) );
body.addClass( className );
// Do good diligence and return an expected value from the function.
deferred = new $.Deferred();
deferred.resolveWith( partial, _.map( partial.placements(), function() {
return \'\';
} ) );
return deferred.promise();
}
});
然后,在PHP中注册partial时,可以使用此自定义类型:
$wp_customize->selective_refresh->add_partial( \'nav_body_class\', array(
\'selector\' => \'nav\',
\'type\' => \'body_class\',
) );
下面是一个完整的插件,演示了该技术:
https://gist.github.com/westonruter/731e3106177ce2b067290ddbe602ce05