定制器实时预览不起作用,刷新但没有任何变化

时间:2017-01-15 作者:Edward

这是我的代码:

// Hooked to "after_setup_theme"
if(get_theme_mod(\'enable_vertical_header\')) {
    // init vertical header, register scripts, style, settings and output html in template
    $vertical_header = new Vertical_Header;
}
我在Customizer中创建了一个复选框选项“enable\\u vertical\\u header”(默认值0),用于打开/关闭垂直标题,当我切换该选项时,实时预览区域会刷新,但不会更改。

通过回显“enable\\u vertical\\u header”的值,我总能看到它null, 如果在前端,这是有意义的。但在Customizer中,应该get_theme_mod 不返回实时值?

更新:控制代码

function my_custom_text_settings( $wp_customize ) {
    $wp_customize->add_section( \'my_section\' , array(
        \'title\'      => __(\'My Section\',\'mytheme\'),
        \'priority\'   => 30,
    ) );

    // Register the settings
    $wp_customize->add_setting( \'enable_vertical_header\', array(
        \'default\'        => 0,
        \'type\'           => \'theme_mod\',
        \'capability\'     => \'edit_theme_options\',
    ) );
    // Add the controls
    $wp_customize->add_control( \'enable_vertical_header\', array(
        \'label\'       => __( \'My custom control\', \'translation_domain\' ),
        \'section\'     => \'my_section\',
        \'settings\'    => \'enable_vertical_header\',
        \'type\'        => \'checkbox\',
        \'priority\'    => 10
    ) );

}
add_action( \'customize_register\', \'my_custom_text_settings\' );

1 个回复
最合适的回答,由SO网友:Edward 整理而成

通过一些实验,我找到了答案。

get_theme_mod 在“after\\u setup\\u theme”或“init”中调用时,不会获得实时值,它在“customize\\u preview\\u init”和“wp\\u loaded”中确实有效,因此工作代码:

add_action(\'customize_preview_init\', \'my_header\' );
function my_header() {
        if(get_theme_mod(\'enable_vertical_header\')) {
            $vertical_header = new Vertical_Header;
        }   
}

相关推荐