Add button to Customizer

There are three things you need to do in particular.

  1. As there are no settings associated with the control, you need to explicitly supply an empty array for settings, as otherwise it will try to look for a setting ID that matches the control ID (here button_id); since that setting never gets created, the control then never finishes initializing. Read more about setting-less controls.
  2. Since the control is going to output an input element with type=button you need to supply the button’s label via the value attribute of that element. You can do this by passing it via the input_attrs attribute.
  3. Similarly, if you want to supply a custom class of button button-primary then you can do so by passing it here as well.

In short, this is what you would be looking at:

$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', // 👈
    ),
) );

Result:

Button control

Naturally this button will do nothing, so then you’d need to hook it up to custom functionality with JS using something like this:

wp.customize.control( 'button_id', function( control ) {
    control.container.find( '.button' ).on( 'click', function() {
        console.info( 'Button was clicked.' );
    } );
} );

As of WordPress 4.9-beta1, you’ll be able to add a control with JS in this way (needs testing!):

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' );
} );

Again, the new JS API needs testing. A dev note will be coming to make.wordpress.org/core.

Leave a Comment