I am trying to access a widget area in the customizer via JS with the intent of getting count of the amount of widgets in the section.

I am able to access some information with the code below but am not quite there.

wp.customize.section( 'sidebar-widgets-sidebar-1', function( section ) {
    console.info( section  );

While you can look at the WidgetControl instances contained inside of a SidebarSection, it is better to instead to look at the underlying setting that lists out the widgets contained inside of the sidebar. So do something like this:

wp.customize( 'sidebars_widgets[sidebar-1]', function( sidebarSetting ) {
    console.info( sidebarSetting.get().length );
} );

Alternatively, with a reusable function:

 * Get the count of widgets in a given sidebar.
 * @param {string} sidebarId Sidebar ID.
 * @returns {jQuery.promise} Resolving with the number of widgets in the sidebar.
function getSidebarWidgetCount( sidebarId ) {
    var deferred = jQuery.Deferred();
    wp.customize( 'sidebars_widgets[' + sidebarId + ']', function( sidebarSetting ) {
        deferred.resolve( sidebarSetting.get().length );
    } );
    return deferred.promise();


getSidebarWidgetCount( 'sidebar-1' ).done( function( count ){
    console.info( count );
} );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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