Add button to Customizer

时间:2017-10-10 作者:Jamie

我试图在主题定制器中添加一个按钮,但无法使其工作。到目前为止,我创建了一个面板,然后它显示了一个部分按钮,但理想情况下,我希望在最后一个面板“附加CSS”的底部有一个普通的蓝色WordPress样式按钮。非常感谢您的帮助。

function prefix_customizer_register( $wp_customize ) {

    $wp_customize->add_panel( \'panel_id\', array(
        \'priority\' => 300,
        \'capability\' => \'edit_theme_options\',
        \'theme_supports\' => \'\',
        \'title\' => __( \'Next Step\', \'textdomain\' ),
        \'description\' => __( \'This is the next step.\', \'textdomain\' ),
    ) );

    $wp_customize->add_section( \'section_id\', array(
        \'priority\' => 10,
        \'capability\' => \'edit_theme_options\',
        \'theme_supports\' => \'\',
        \'title\' => __( \'Edit Pages\', \'textdomain\' ),
        \'description\' => \'\',
        \'panel\' => \'panel_id\',
    ) );

    $wp_customize->add_setting( \'url_field_id\', array(
        \'default\' => \'\',
        \'type\' => \'theme_mod\',
        \'capability\' => \'edit_theme_options\',
        \'transport\' => \'\',
        \'sanitize_callback\' => \'esc_url\',
    ) );

    $wp_customize->add_control( \'button_id\', array(
        \'type\' => \'button\',
        \'priority\' => 10,
        \'section\' => \'section_id\',
        \'label\' => __( \'Edit Pages\', \'textdomain\' ),
        \'description\' => \'\',
    ) );

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

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

你需要特别做三件事。

由于没有与控件关联的设置,因此需要为settings, 否则,它将尝试查找与控件ID匹配的设置ID(此处button_id); 由于从未创建该设置,因此控件永远不会完成初始化。了解更多信息setting-less controls.input 具有的元素type=button 您需要通过提供按钮标签value 该元素的属性。您可以通过input_attrs 属性class 属于button button-primary 然后您也可以通过将其传递到此处来实现

$wp_customize->add_control( \'button_id\', array(
    \'type\' => \'button\',
    \'settings\' => array(), // 
    \'priority\' => 10,
    \'section\' => \'section_id\',
    \'input_attrs\' => array(
        \'value\' => __( \'Edit Pages\', \'textdomain\' ), // 
        \'class\' => \'button button-primary\', // 
    ),
) );
结果:

Button control

很自然,这个按钮什么都不会做,因此您需要使用JS将其连接到自定义功能,如下所示:

wp.customize.control( \'button_id\', function( control ) {
    control.container.find( \'.button\' ).on( \'click\', function() {
        console.info( \'Button was clicked.\' );
    } );
} );
从WordPress 4.9-beta1开始,您就可以通过这种方式使用JS添加控件(需要测试!):

var control = new wp.customize.Control( \'button_id\', {
    type: \'button\',
    settings: [],
    section: \'section_id\',
    inputAttrs: {
        value: \'Edit Pages\',
        \'class\': \'button button-primary\'
    }
} );
wp.customize.control.add( control );
control.container.find( \'.button\' ).on( \'click\', function() {
    console.info( \'Button was clicked\' );
} );
同样,新的JS API需要测试。将在make.wordpress.org/core.

结束

相关推荐