[WordPress]ウィジェットが有効・無効になっているかを判定し条件分岐で処理をするスニペット

  • 更新日:
  • 公開日:

Warning: Undefined array key 2 in /home/xs390735/increment-log.com/public_html/wp-content/themes/increment-log/functions.php on line 349

Warning: Undefined array key 4 in /home/xs390735/increment-log.com/public_html/wp-content/themes/increment-log/functions.php on line 354

Warning: Undefined array key 6 in /home/xs390735/increment-log.com/public_html/wp-content/themes/increment-log/functions.php on line 359

ウィジェットが無効化されている場合にHTMLを出力したい状況になったのでメモ。

ウィジェットが有効・無効になっているかを判定する

ウィジェットが有効・無効になっているかどうかを判定するには、WordPress側で用意されているis_active_sidebar()という関数を使います。ちなみにウィジェットが一切設定されていない状態が無効状態です。(逆に一つでもウィジェットが設定されていると有効状態です)

<?php if( is_active_sidebar('widget-name') ) : 

 dynamic_sidebar( 'widget-name' );

else : ?>

 //ウィジェットが設定されていない場合(無効化状態)
 <p>ウィジェット無いです</p>

<?php endif; ?>

 is_active_sidebar()の引数に登録したウィジェットのIDを渡すとtrueかfalseを返してくれるので、これで条件分岐します。ウィジェットのIDというのは、register_sidebar()で登録するときに指定する値です。

register_sidebar( array(
 'name' => 'サイドバー',
 'id' => 'sidebar-name',
 'before_widget' => '<div id="%1$s" class="widget-container %2$s">',
 'after_widget' => '</div>',
 'before_title' => '<h3 class="widget-title">',
 'after_title' => '</h3>'
) );

ウィジェットはこんな感じで登録すると思いますが、上の例で言えば3行目の「’id’ => ‘sidebar-name’」がウィジェットのIDになります。

参考:

is_active_sidebar:WordPress私的マニュアル

書いた人

Symbol Mark

Ryoichi

除菌ティッシュを買い込んで使いきれずによく乾かす人。

※2019年10月16日現在ブログリニューアル中です。崩れなどが発生していたらすみません。

うぇぶ: @s_ryone