我的背景颜色定制器不起作用

时间:2016-08-02 作者:mheonyae

我添加了一些自定义设置,但似乎不起作用。

这是我的html:

<div class="section-one">
<h2>section 1</h2>
</div>
样式中的默认css。css:

/*content sections*/
.section-one{
    height: 300px;
    width:100%;
    background-color: #fff;
    color: blue;
}
以及我添加的自定义程序功能:

function mr_customizer_register($wp_customize){
    $wp_customize->add_section(\'CMWP_colors\', array(
        \'title\' => __(\'Colors\', \'CMWP\'),
        \'description\' => \'Modify the theme colors\'
    ));

    $wp_customize->add_setting(\'sec1_background_color\', array(
        \'default\' => \'#ffffff\',
    ));
    $wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, \'sec1_background_color\', array(
        \'label\' => __(\'Edit section 1 background color\', \'CMWP\'),
        \'section\' => \'CMWP_colors\',
        \'settings\' => \'sec1_background_color\'
    ) ));

}
添加设置后,我可以选择颜色,但网站上没有任何更改,可能有什么问题?

1 个回复
SO网友:cybmeta

如果在customizer中注册设置,它会在customizer面板中添加UI,并将选项值存储在数据库中,但它不知道应该在站点中更改什么。你必须use the value of that setting in the frontend in the way you wish.

例如,在您的情况下,可能是这样的:

add_action( \'wp_enqueue_scripts\', \'cyb_dinamic_styles\' );
function cyb_dinamic_styles() {
    wp_enqueue_style( \'my-style\', get_stylesheet_uri(), array(), \'1.0\' );
    $color = get_theme_mod( \'sec1_background_color\', \'#ffffff\' );
    $custom_css = "
                .section-one{
                        background: $color;
                }";
     wp_add_inline_style( \'my-style\', $custom_css );
}
或者像这样:

add_action( \'wp_head\', \'cyb_head_styles\' );
function cyb_head_styles() {
    $color = get_theme_mod( \'sec1_background_color\', \'#ffffff\' );
    ?>
    <style>
        .section-one {
             background: <?php echo $color; ?>
         }
    </style>
    <?php
}
此外,如果希望允许在customizer屏幕中实时预览更改,则需要创建一个JavaScript代码段,以扩展wp.customize:

( function( $ ) {

    // Update background color of .section-one with the
    // value of sec1_background_color setting
    wp.customize( \'sec1_background_color\', function( value ) {
        value.bind( function( newval ) {
            $(\'.section-one\').css(\'color\', newval );
        } );
    } );

} )( jQuery );
最后,您需要在customizer屏幕中包含此JavaScript。例如:

add_action( \'customize_preview_init\', \'cyb_customizer_live_preview\' );
function cyb_customizer_live_preview() {
    wp_enqueue_script( 
          \'mytheme-customizer\',
          get_template_directory_uri().\'/js/mytheme-customizer.js\',
          array( \'jquery\',\'customize-preview\' ), // Define dependencies
          \'1.0\'
    );
}

相关推荐