プログラムでウィジェットを2つのサイドバーに追加したいと思います。公式の方法が見つかりませんでしたか?
データベースを調べ始めました。サイドバーにウィジェットを配置するのは「sidebars_widgets」オプションであることがわかりました。オプションを見ると、ウィジェット名には末尾に「widget_name-6」のような番号が追加されています。その番号はどこから来たのですか?
これを修正する方法についてのアイデアはありますか?
プログラムでウィジェットを2つのサイドバーに追加したいと思います。公式の方法が見つかりませんでしたか?
データベースを調べ始めました。サイドバーにウィジェットを配置するのは「sidebars_widgets」オプションであることがわかりました。オプションを見ると、ウィジェット名には末尾に「widget_name-6」のような番号が追加されています。その番号はどこから来たのですか?
これを修正する方法についてのアイデアはありますか?
回答:
私がこの答えを始めたとき、それはほんの小さなメモであるべきです。まあ、私は失敗しました。ごめんなさい!私と一緒にいて、奥深くに隠れた良いものがあります…
ウィジェットのリストはというオプションに保存されます'sidebars_widgets'。A var_export()は次のようなものを与えます:
array (
  'wp_inactive_widgets' => 
  array (
  ),
  'top-widget' => 
  array (
  ),
  'bottom-widget' => 
  array (
  ),
  'array_version' => 3,
)
無視'wp_inactive_widgets'し'array_version'ます。それらを気にする必要はありません。
他のキーは、登録されたサイドバーの識別子です。この場合、サイドバーは次のコードで登録されている可能性があります。
// Register two sidebars.
$sidebars = array ( 'a' => 'top-widget', 'b' => 'bottom-widget' );
foreach ( $sidebars as $sidebar )
{
    register_sidebar(
        array (
            'name'          => $sidebar,
            'id'            => $sidebar,
            'before_widget' => '',
            'after_widget'  => ''
        )
    );
}
デフォルトでは、登録後、サイドバーは空です。もちろん。
登録されたウィジェットクラスごとに、必要なすべてのオプションを含む個別のオプションが作成されます。オプションの先頭には文字列が付きますwidget_。すべてのアクティブなRSSウィジェットのオプションを取得するには、調査する必要があります…
get_option( 'widget_rss' );可能な出力:
array (
  2 => 
  array (
    'title' => 'WordPress Stack Exchange',
    'url' => 'http://wordpress.stackexchange.com/feeds',
    'link' => 'http://wordpress.stackexchange.com/questions',
    'items' => 5,
    'show_summary' => 1,
    'show_author' => 0,
    'show_date' => 0,
  ),
)
番号2に注意してください。複数のインスタンスの引数はすべて、番号でソートされたこの1つのオプションに格納されます。
WordPressが既に認識しているウィジェットクラスを確認wp-admin/options.phpするには、次のように表示されるまで下にスクロールします。

はい、シリアル化されたデータ。いいえ、ここでは読むことができません。心配しないで、あなたはする必要はありません。
内部の仕組みをよりよく説明するために、非常に単純なデモウィジェットを作成しました。
/**
 * Super simple widget.
 */
class T5_Demo_Widget extends WP_Widget
{
    public function __construct()
    {                      // id_base        ,  visible name
        parent::__construct( 't5_demo_widget', 'T5 Demo Widget' );
    }
    public function widget( $args, $instance )
    {
        echo $args['before_widget'], wpautop( $instance['text'] ), $args['after_widget'];
    }
    public function form( $instance )
    {
        $text = isset ( $instance['text'] )
            ? esc_textarea( $instance['text'] ) : '';
        printf(
            '<textarea class="widefat" rows="7" cols="20" id="%1$s" name="%2$s">%3$s</textarea>',
            $this->get_field_id( 'text' ),
            $this->get_field_name( 'text' ),
            $text
        );
    }
}
コンストラクタに注意してください:'t5_demo_widget'は、$id_baseこのウィジェットの識別子です。スクリーンショットでわかるように、引数はオプションに保存されていますwidget_t5_demo_widget。すべてのカスタムウィジェットはこのように扱われます。名前を推測する必要はありません。ので、あなたがあなたのウィジェットを書かれている(おそらく)あなたのクラスのすべての引数から知っている$instanceパラメータを。
最初に、いくつかのサイドバーとカスタムウィジェットを登録する必要があります。これに対する適切なアクションは覚えやすい:'widgets_init'。すべてをコンテナに入れます–クラスまたは関数。簡単にするために、という名前の関数を使用しますt5_default_widget_demo()。
次のコードはすべてになりますfunctions.php。クラスT5_Demo_Widgetはすでにロードされているはずです。同じファイルに入れただけです…
add_action( 'widgets_init', 't5_default_widget_demo' );
function t5_default_widget_demo()
{
    // Register our own widget.
    register_widget( 'T5_Demo_Widget' );
    // Register two sidebars.
    $sidebars = array ( 'a' => 'top-widget', 'b' => 'bottom-widget' );
    foreach ( $sidebars as $sidebar )
    {
        register_sidebar(
            array (
                'name'          => $sidebar,
                'id'            => $sidebar,
                'before_widget' => '',
                'after_widget'  => ''
            )
        );
    }
これまでのところ、とても簡単です。これでウィジェットの準備が整いました。デモウィジェットは既知です。今から楽しみ。
$active_widgets = get_option( 'sidebars_widgets' );
if ( ! empty ( $active_widgets[ $sidebars['a'] ] )
    or ! empty ( $active_widgets[ $sidebars['b'] ] )
)
{   // Okay, no fun anymore. There is already some content.
    return;
}
あなたは本当にユーザー設定を破壊したくありません。すでにサイドバーにコンテンツがある場合は、コードを実行しないでください。そのため、この場合は停止します。
さて、サイドバーが空であると仮定して...カウンターが必要です:
$counter = 1;ウィジェットには番号が付けられています。これらの番号は、WordPressの2番目の識別子です。
変更する配列を取得しましょう:
$active_widgets = get_option( 'sidebars_widgets' );カウンターも必要です(これについては後で説明します)。
$counter = 1;そして、カウンター、サイドバー名、ウィジェット引数の使用方法を以下に示します(引数は1つだけですtext)。
// Add a 'demo' widget to the top sidebar …
$active_widgets[ $sidebars['a'] ][0] = 't5_demo_widget-' . $counter;
// … and write some text into it:
$demo_widget_content[ $counter ] = array ( 'text' => "This works!\n\nAmazing!" );
$counter++;
ウィジェット識別子の作成方法に注意してください:、id_baseマイナス-、カウンター。ウィジェットのコンテンツは別の変数に保存されます$demo_widget_content。キーとウィジェットの引数が配列に格納されているカウンターは次のとおりです。
衝突を避けるために完了したら、カウンターを1つ増やします。
それは簡単でした。RSSウィジェットになりました。より多くのフィールド、もっと楽しく!
$active_widgets[ $sidebars['a'] ][] = 'rss-' . $counter;
// The latest 15 questions from WordPress Stack Exchange.
$rss_content[ $counter ] = array (
    'title'        => 'WordPress Stack Exchange',
    'url'          => 'http://wordpress.stackexchange.com/feeds',
    'link'         => 'http://wordpress.stackexchange.com/questions',
    'items'        => 15,
    'show_summary' => 0,
    'show_author'  => 1,
    'show_date'    => 1,
);
update_option( 'widget_rss', $rss_content );
$counter++;
ここに何か新しいものがあります:update_option()これはRSSウィジェットの引数を別のオプションに保存します。WordPressはこれらを後で自動的に見つけます。
2番目のサイドバーに2番目のインスタンスを追加したため、デモウィジェットの引数は保存しませんでした…
// Okay, now to our second sidebar. We make it short.
$active_widgets[ $sidebars['b'] ][] = 't5_demo_widget-' . $counter;
#$demo_widget_content = get_option( 'widget_t5_demo_widget', array() );
$demo_widget_content[ $counter ] = array ( 'text' => 'The second instance of our amazing demo widget.' );
update_option( 'widget_t5_demo_widget', $demo_widget_content );
...そして、すべての引数をまとめて保存しますt5_demo_widget。同じオプションを2回更新する必要はありません。
さて、今日のための十分なウィジェットsidebars_widgetsも保存しましょう。
update_option( 'sidebars_widgets', $active_widgets );これで、WordPressは、登録されたウィジェットがいくつかあり、各ウィジェットの引数が保存されていることを認識します。var_export()sidebar_widgetsのA は次のようになります。
array (
  'wp_inactive_widgets' => 
  array (
  ),
  'top-widget' => 
  array (
    0 => 't5_demo_widget-1',
    1 => 'rss-2',
  ),
  'bottom-widget' => 
  array (
    0 => 't5_demo_widget-3',
  ),
  'array_version' => 3,
)
add_action( 'widgets_init', 't5_default_widget_demo' );
function t5_default_widget_demo()
{
    // Register our own widget.
    register_widget( 'T5_Demo_Widget' );
    // Register two sidebars.
    $sidebars = array ( 'a' => 'top-widget', 'b' => 'bottom-widget' );
    foreach ( $sidebars as $sidebar )
    {
        register_sidebar(
            array (
                'name'          => $sidebar,
                'id'            => $sidebar,
                'before_widget' => '',
                'after_widget'  => ''
            )
        );
    }
    // Okay, now the funny part.
    // We don't want to undo user changes, so we look for changes first.
    $active_widgets = get_option( 'sidebars_widgets' );
    if ( ! empty ( $active_widgets[ $sidebars['a'] ] )
        or ! empty ( $active_widgets[ $sidebars['b'] ] )
    )
    {   // Okay, no fun anymore. There is already some content.
        return;
    }
    // The sidebars are empty, let's put something into them.
    // How about a RSS widget and two instances of our demo widget?
    // Note that widgets are numbered. We need a counter:
    $counter = 1;
    // Add a 'demo' widget to the top sidebar …
    $active_widgets[ $sidebars['a'] ][0] = 't5_demo_widget-' . $counter;
    // … and write some text into it:
    $demo_widget_content[ $counter ] = array ( 'text' => "This works!\n\nAmazing!" );
    #update_option( 'widget_t5_demo_widget', $demo_widget_content );
    $counter++;
    // That was easy. Now a RSS widget. More fields, more fun!
    $active_widgets[ $sidebars['a'] ][] = 'rss-' . $counter;
    // The latest 15 questions from WordPress Stack Exchange.
    $rss_content[ $counter ] = array (
        'title'        => 'WordPress Stack Exchange',
        'url'          => 'http://wordpress.stackexchange.com/feeds',
        'link'         => 'http://wordpress.stackexchange.com/questions',
        'items'        => 15,
        'show_summary' => 0,
        'show_author'  => 1,
        'show_date'    => 1,
    );
    update_option( 'widget_rss', $rss_content );
    $counter++;
    // Okay, now to our second sidebar. We make it short.
    $active_widgets[ $sidebars['b'] ][] = 't5_demo_widget-' . $counter;
    #$demo_widget_content = get_option( 'widget_t5_demo_widget', array() );
    $demo_widget_content[ $counter ] = array ( 'text' => 'The second instance of our amazing demo widget.' );
    update_option( 'widget_t5_demo_widget', $demo_widget_content );
    // Now save the $active_widgets array.
    update_option( 'sidebars_widgets', $active_widgets );
}
ここに行くと、wp-admin/widgets.php3つのプリセットウィジェットが表示されます。

以上です。つかいます …
dynamic_sidebar( 'top-widget' );
dynamic_sidebar( 'bottom-widget' );
…ウィジェットを印刷します。
小さな不具合があります:初期登録のためにフロントエンドを2回ロードする必要があります。誰かがここで手伝うことができれば、私は非常に感謝します。
widget_t5_demo_widgetここで何を参照しますupdate_option( 'widget_t5_demo_widget', $demo_widget_content );か?
                    ソリューションを共有していただきありがとうございます。この質問で説明した内容を使用して、サイドバーを非常に簡単に初期化するために使用できるコードを作成しました。非常に柔軟で、コードをまったく変更することなく、必要なだけウィジェットを作成できます。フィルターフックを使用して、配列の引数を渡すだけです。コメントされたコードは次のとおりです。
function initialize_sidebars(){
  $sidebars = array();
  // Supply the sidebars you want to initialize in a filter
  $sidebars = apply_filters( 'alter_initialization_sidebars', $sidebars );
  $active_widgets = get_option('sidebars_widgets');
  $args = array(
    'sidebars' => $sidebars,
    'active_widgets' => $active_widgets,
    'update_widget_content' => array(),
  );
  foreach ( $sidebars as $current_sidebar_short_name => $current_sidebar_id ) {
    $args['current_sidebar_short_name'] = $current_sidebar_short_name;
    // we are passing our arguments as a reference, so we can modify their contents
    do_action( 'your_plugin_sidebar_init', array( &$args ) );
  }
  // we only need to update sidebars, if the sidebars are not initialized yet
  // and we also have data to initialize the sidebars with
  if ( ! empty( $args['update_widget_content'] ) ) {
    foreach ( $args['update_widget_content'] as $widget => $widget_occurence ) {
      // the update_widget_content array stores all widget instances of each widget
      update_option( 'widget_' . $widget, $args['update_widget_content'][ $widget ] );
    }
    // after we have updated all the widgets, we update the active_widgets array
    update_option( 'sidebars_widgets', $args['active_widgets'] );
  }
}
これは、サイドバーに既にコンテンツが含まれているかどうかを確認するヘルパー関数です。
function check_sidebar_content( $active_widgets, $sidebars, $sidebar_name ) {
  $sidebar_contents = $active_widgets[ $sidebars[ $sidebar_name ] ];
  if ( ! empty( $sidebar_contents ) ) {
    return $sidebar_contents;
  }
  return false;
}
ここで、「sidebar_init」アクションにフックされる関数を作成する必要があります。
add_action( 'your_plugin_sidebar_init', 'add_widgets_to_sidebar' );
function add_widgets_to_sidebar( $args ) {
  extract( $args[0] );
  // We check if the current sidebar already has content and if it does we exit
  $sidebar_element = check_sidebar_content( $active_widgets, $sidebars, $current_sidebar_short_name );
  if ( $sidebar_element !== false  ) {
    return;
  }
  do_action( 'your_plugin_widget_init', array( &$args ) );
}
そして今、ウィジェットの初期化:
add_action( 'your_plugin_widget_init', 'your_plugin_initialize_widgets' );
function your_plugin_initialize_widgets( $args ) {
  extract( $args[0][0] );
  $widgets = array();
  // Here the widgets previously defined in filter functions are initialized,
  // but only those corresponding to the current sidebar 
  $widgets = apply_filters( 'alter_initialization_widgets_' . $current_sidebar_short_name, $widgets );
  if ( ! empty( $widgets ) ) {
    do_action( 'create_widgets_for_sidebar', array( &$args ), $widgets );
  }
}
最後のアクションは、各サイドバーにウィジェットを作成することです。
add_action( 'create_widgets_for_sidebar', 'your_plugin_create_widgets', 10, 2 );
function your_plugin_create_widgets( $args, $widgets ) {
  extract( $args[0][0][0] );
  foreach ( $widgets as $widget => $widget_content ) {
    // The counter is increased on a widget basis. For instance, if you had three widgets,
    // two of them being the archives widget and one of the being a custom widget, then the
    // correct counter appended to each one of them would be archive-1, archive-2 and custom-1.
    // So the widget counter is not a global counter but one which counts the instances (the
    // widget_occurrence as I have called it) of each widget.
    $counter = count_widget_occurence( $widget, $args[0][0][0]['update_widget_content'] );
    // We add each instance to the active widgets...
    $args[0][0][0]['active_widgets'][ $sidebars[ $current_sidebar_short_name ] ][] = $widget . '-' . $counter;
    // ...and also save the content in another associative array.
    $args[0][0][0]['update_widget_content'][ $widget ][ $counter ] = $widget_content;
  }
}
この関数は、特定のウィジェットのインスタンスが既に定義されている数を追跡するために使用されます。
function count_widget_occurence( $widget, $update_widget_content ) {
  $widget_occurrence = 0;
  // We look at the update_widget_content array which stores each
  // instance of the current widget with the current counter in an 
  // associative array. The key of this array is the name of the 
  // current widget.
      // Having three archives widgets for instance would look like this:
      // 'update_widget_content'['archives'] => [1][2][3] 
  if ( array_key_exists( $widget, $update_widget_content ) ) {
    $widget_counters = array_keys( $update_widget_content[ $widget ] );
    $widget_occurrence = end( $widget_counters );
  }
  $widget_occurrence++;
  return $widget_occurrence;
}
最後に行う必要があるのは、実際に値を割り当てることです。次のフィルター関数を使用します。
add_filter( 'alter_initialization_sidebars', 'current_initialization_sidebars' ) ;
// Use this filter hook to specify which sidebars you want to initialize
function current_initialization_sidebars( $sidebars ) {
  // The sidebars are assigned in this manner.
  // The array key is very important because it is used as a suffix in the initialization function
  // for each sidebar. The value is what is used in the html attributes.
  $sidebars['info'] = 'info-sidebar';
  return $sidebars;
}
そして:
add_filter( 'alter_initialization_widgets_info', 'current_info_widgets' );
// Add a filter hook for each sidebar you have. The hook name is derived from
// the array keys passed in the alter_initialization_sidebars filter. 
// Each filter has a name of 'alter_initialization_widgets_' and the array 
// key appended to it.
function current_info_widgets( $widgets ) {
  // This filter function is used to add widgets to the info sidebar. Add each widget
  // you want to assign to this sidebar to an array.
  return $widgets = array(
    // Use the name of the widget as specified in the call to the WP_Widget constructor
    // as the array key.
    // The archives widget is a widget which is shipped with wordpress by default.
    // The arguments used by this widget, as all other default widgets, can be found
    // in wp-includes/default-widgets.php. 
    'archives' => array(
      // Pass in the array options as an array
      'title' => 'Old Content',
      'dropdown' => 'on',
      // The 'on' value is arbitrarily chosen, the widget actually only checks for
      // a non-empty value on both of these options
      'count' => 'on',
    ),
 );
}
理想的には、次のようなプラグインまたはテーマのアクティブ化時に呼び出されるセットアップ関数でinitialize_sidebarsを呼び出します。テーマのアクティブ化:
add_action( 'after_switch_theme', 'my_activation_function' );
function my_activation_function() {
  initialize_sidebars();
}
プラグインのアクティベーション:
register_activation_hook( __FILE__, 'my_activation_function' );
function my_activation_function() {
  initialize_sidebars();
}
この関数の集合体の使用法を要約するには:
「alter_initialization_sidebars」フィルターにフックされるサイドバーを初期化する関数を作成します。
「alter_initialization_widgets_ $ sidebarname」フィルターにフックされる追加した各サイドバーに対して関数を作成します。$ sidebarnameをステップ1で作成した各サイドバーの名前に置き換えます。
また、このコメント解除されたコードを関数ファイルにコピーして、すぐにフィルター関数の作成を開始することもできます。pastieのコード(初期化フィルター関数なし)
まず第一に、詳細な回答をしてくれた@toschoに感謝します。
これは、シンプルなソリューションとデフォルトのウィジェットオプションを探している人向けのシンプルな例です。
$active_sidebars = get_option( 'sidebars_widgets' ); //get all sidebars and widgets
$widget_options = get_option( 'widget_name-1' );
$widget_options[1] = array( 'option1' => 'value', 'option2' => 'value2' );
if(isset($active_sidebars['sidebar-id']) && empty($active_sidebars['sidebar-id'])) { //check if sidebar exists and it is empty
    $active_sidebars['sidebar-id'] = array('widget_name-1'); //add a widget to sidebar
    update_option('widget_name-1', $widget_options); //update widget default options
    update_option('sidebars_widgets', $active_sidebars); //update sidebars
}注1:sidebar-idウィジェットメニューに移動して、目的のサイドバーを調べることができます。最初<div id="widgets-holder-wrap">の<div>子供にはsidebar-id。
注2:widget_nameウィジェットメニューに移動して、目的のウィジェットを調べることができます。次のようなものが表示されます<div id="widget-6_widget_name-__i__" class="widget ui-draggable">。
役に立てば幸いです。
これがあなたのやり方です:
(警告、元のウィジェットをwidgets配列に戻さなかった場合、以前のすべてのウィジェットが削除される可能性があります。)
    $widgets = array(
    'middle-sidebar' => array(
        'widget_name'
    ),
    'right-sidebar' => array(
        'widget2_name-1'
    )
);
update_option('sidebars_widgets', $widgets);-numberは、後で次のようなオプションを使用してウィジェットにオプションを追加する場合に使用できます。
    update_option('widget_widget_name', array(
    1 => array(
        'title' => 'The tile',
        'number' => 4
    ),
    '_multiwidget' => 1
));$widgets = get_option( 'sidebars_widgets' );