web-dev-qa-db-ja.com

カスタマイザーJSを介してサイドバーに含まれるウィザードの数を決定する方法

セクション内のウィジェットの数を数える目的で、JSを介してカスタマイザ内のウィジェット領域にアクセスしようとしています。

以下のコードでいくつかの情報にアクセスすることができますが、そこにはありません。

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

canWidgetControlの中に含まれるSidebarSectionインスタンスを見ることができますが、代わりにサイドバーの中に含まれるウィジェットをリストする基礎となるsettingを見ることをお勧めします。だから、このようなことをする:

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

あるいは、再利用可能な機能を使って:

/**
 * 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 );
} );
2
Weston Ruter