Okay so I have been trying to educate myself to create new panels sections and controls dynamically using customizer’s JS API.

It has been frustrating few days and I was unable to get the exact way to achieve this via JS API.

So far, this is some thing I am doing to make it happen but with no success:

    // for Settings
    api.create( 
        params.id, 
        params.id, 
        params.default, 
        params.args 
    );

    // for controls
    var controlConstructor = api.controlConstructor[params.type];
    var control = new controlConstructor(params.id, {
        params: params,
        previewer: api.previewer
    });
    api.control.add( 
        params.id, 
        control 
    );

     //for Sections
     var section = new api.Section(params.id, { 
        params: params
     }); 
    api.section.add( params.id, section );
    api.section('section_id').activate();

None of them seem to work as the section doesn’t appear and I have to run api.section('section_id').activate() twice in console to make the section appear, the same is with control.

2 s
2

1) Maybe bind to the api.ready state which may fix having to call your section twice

(function($, api){
  api.bind( 'ready', function() {...

  }
})(jQuery);

I saw a note in trac that said “Note that the APIs for dynamically-added controls, and APIs for JS-templated custom Sections and Panels are not yet available as of WordPress 4.2. See #30741.” Reading that trac ends with “likely not for 4.5 right now” so your efforts may be futile =(

2) For reference, the wp_customize JS API can be found here. This link may be useful as well.

3) I don’t have enough rep for a third link but you might look at Kirki.org which is a helper framework for customizer fields. Kirki is pretty active on Github too.

4) On the PHP side, you can use the “active_callback” option on your field array to dynamically present fields.

$wp_customize->add_control( 'some_single_page_specific_option', array(
  'label'           => esc_html__( 'Single Page Option' ),
  'section'         => 'my_page_options',
  'active_callback' => 'if_is_singular',
));

function if_is_singular(){
  if( is_singular() ){
    return true;
  } else {
    return false;
  }
}

Good luck.

Leave a Reply

Your email address will not be published. Required fields are marked *