Where to get the unsaved list of widgets in customizer?

In the customizer, whenever I add a new widget (but before I save/publish the changes) I would like to get the number of widgets in that sidebar area.

Once the changes have been saved and the widgets are saved to the DB, I can use the wp_get_sidebars_widgets (called in the init hook, where it registers my widgets) to count all the widgets for each sidebar area,

I’ve taken a look at the wp.customize.Widgets and the wp.customize.WidgetCustomizerPreview objects and they do not look like they will give me what I need. Where in the JS is this information saved?

1 Answer
1

You can get the list of widgets in a sidebar via:

wp.customize('sidebars_widgets[sidebar-1]').get()

This is a list of the widgets’ IDs. The sidebars_widgets[sidebar-1] is the setting ID for the sidebar. Replace sidebar-1 with the ID of your sidebar.

So to get the count just do:

wp.customize('sidebars_widgets[sidebar-1]').get().length

If you want to listen for when a widget is added or removed to a sidebar, you can bind to the setting to listen for changes, like this:

wp.customize( 'sidebars_widgets[sidebar-1]', function( sidebarSetting ) {
    sidebarSetting.bind( function( newWidgetIds, oldWidgetIds ) {
        console.info( {
            added: _.difference( newWidgetIds, oldWidgetIds ),
            removed: _.difference( oldWidgetIds, newWidgetIds )
        } );
    } )
} );

Leave a Comment