First, in order to enqueue JS in the customizer controls, you need to use the customize_controls_enqueue_scripts
action. This is different than the action used to enqueue scripts into the customizer preview, which is what themes normally do via customize_preview_init
or wp_enqueue_scripts
. So in your snippet above, replace customize_preview_init
with customize_controls_enqueue_scripts
.
Secondly, in order to extend a control in the customizer you need to wait for the control to be initialized. Controls may be added and removed dynamically in the course of a customizer session, so you cannot just query the DOM once the page is ready. Your custom control should implement a corresponding JS wp.customize.Control
subclass that is responsible for setting up Select2. For example, if you have:
class My_Select2_Control extends WP_Customize_Control {
public $type="my_select2";
/* ... */
}
Then you should have a JS file that also contains:
wp.customize.controlConstructor.my_select2 = wp.customize.Control.extend( {
ready: function() {
var control = this;
wp.customize.Control.prototype.ready.call( control );
// Set up select2 control in this.container...
}
} );
Enqueue this file at customize_controls_enqueue_scripts
with customize-controls
and select2
as its script dependencies.