Is it Possible to Extend WP Customize JS Methods?

I will enhance my small comment on your question. But again the hint; I’m not a JS expert. The follow source, hints was only used on playing with the Customizer for different checks, examples, like my sandbox.

wp.customize

Understanding the WP theme customizer interface centers around understanding the wp.customize javascript object. The wp.customize object is important and you should set it on the start.

Live Example

The follow small example demonstrate this. At first I set the var api to the object of the customizer. After this I set my custom fields to the api and enhance this with small jQuery source to refresh the result for live preview.

( function( $ ) {
    var api = wp.customize;

    // Site title and description.
    api( 'blogname', function( value ) {
        value.bind( function( to ) {
            $( '#header h1 a, #footer a.site-name' ).html( to );
        } );
    } );

    api( 'blogdescription', function( value ) {
        value.bind( function( to ) {
            $( '#header p.site-description' ).html( to );
        } );
    } );

} )( jQuery );

Settings and Controls

Control objects are stored in wp.customize.control and setting objects are stored in wp.customize.
The value class have a lot of functions, there can help you.

  • instance( id ) – Get an object from the collection with the specified id.
  • has( id ) – Return true, if the collection contains an object with the specified id and it false otherwise.
  • add( id, value ) – Add an object to the collection with an specified id and value.
  • remove( id ) – Remove the object from the collection.
  • create( id ) – Create a new object, using the default constructor and add it to the collection.
  • each( callback, context ) – Iterate over the elements within the collection.

Custom settings

With this functions we can enhance our custom settings.

var api = wp.customize,
    mysetting = api.instance( 'my_custom_setting' );

also usable for an array

var api = wp.customize,
    mysetting = api.instance( 'my_custom_settings[my_custom_setting_field]' );

Get

See the result in the console.

console.log( api.instance( 'my_custom_settings[my_custom_setting_field]' ).get() );

Set

You can also change the setting values via function set.

api.instance( 'my_custom_settings[my_custom_setting_field]' ).set( 'my new value' ) );

Get with the control, as object

console.log( api.control.instance( 'my_custom_setting_field' ) );

Helpful Source

  • wp-admin/js/customize-controls.js
  • wp-includes/js/customize-preview.js
  • wp-includes/js/customize-base.js

Leave a Comment