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:


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:


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 )
        } );
    } )
} );
  • related question, whats the listener / event for when widgets are added or removed. Im trying to count the widgets in a sidebar whenever they are changed.
    – rugbert
    Commented Feb 3, 2018 at 21:07
  • I amended my answer with how to listen for changes to a setting. Commented Feb 3, 2018 at 21:15
  • awesome, thanks Weston! Side question - whats the best place to find documentation for these types of things? The docs on wp.org mostly cover adding controls and such, but what about things like listening for when a widget has just been added to the preview? Or will that be covered in the js docs initiative?
    – rugbert
    Commented Feb 5, 2018 at 0:29
  • The best place for such docs is pretty much right here on WPSE. The handbook docs do need to be fleshed out, but there are so many scenarios that it is hard to distill them. I did give a talk about the fundamentals that I think could serve as the basis of a Customizer JS docs update: weston.ruter.net/2017/12/11/… Commented Feb 5, 2018 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.